欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  移动技术

值得收藏的iOS开发常用代码块

程序员文章站 2023-12-20 09:17:22
遍历可变数组的同时删除数组元素 nsmutablearray *copyarray = [nsmutablearray arraywitharray:arra...

遍历可变数组的同时删除数组元素

nsmutablearray *copyarray = [nsmutablearray arraywitharray:array];  
nsstring *str1 = @“zhangsan”; 
for (addressperson *pername in copyarray) { 
  if ([[pername name] isequaltostring:str1]) { 
    [array removeobject:pername]; 
  } 
} 

获取系统当前语言

nsstring *currentlanguage = [[nslocale preferredlanguages] objectatindex:0];
nslog(@"currentlanguage = %@",currentlanguage);

if ([currentlanguage containsstring:@"zh-hans"]) {
  nslog(@"zh-hans简体中文");
}else if ([currentlanguage containsstring:@"zh-hant"]) {
  nslog(@"zh-hant繁体中文");
}

uitableview的group样式下顶部空白处理

uiview *view = [[uiview alloc] initwithframe:cgrectmake(0, 0, 0, 0.1)];
self.tableview.tableheaderview = view;

uitableview的plain样式下,取消区头停滞效果

- (void)scrollviewdidscroll:(uiscrollview *)scrollview
{
  cgfloat sectionheaderheight = sectionhead.height;
  if (scrollview.contentoffset.y<=sectionheaderheight&&scrollview;.contentoffset.y>=0)
  {
    scrollview.contentinset = uiedgeinsetsmake(-scrollview.contentoffset.y, 0, 0, 0);
  }
  else if(scrollview.contentoffset.y>=sectionheaderheight)
  {
    scrollview.contentinset = uiedgeinsetsmake(-sectionheaderheight, 0, 0, 0);
  }
}

获取某个view所在的控制器

- (uiviewcontroller *)viewcontroller
{
 uiviewcontroller *viewcontroller = nil; 
 uiresponder *next = self.nextresponder;
 while (next)
 {
  if ([next iskindofclass:[uiviewcontroller class]])
  {
   viewcontroller = (uiviewcontroller *)next;   
   break;  
  }  
  next = next.nextresponder; 
 } 
  return viewcontroller;
}
 

两种方法删除nsuserdefaults所有记录

//方法一
nsstring *appdomain = [[nsbundle mainbundle] bundleidentifier];
[[nsuserdefaults standarduserdefaults] removepersistentdomainforname:appdomain];


//方法二
- (void)resetdefaults
{
  nsuserdefaults * defs = [nsuserdefaults standarduserdefaults];
  nsdictionary * dict = [defs dictionaryrepresentation];
  for (id key in dict)
  {
    [defs removeobjectforkey:key];
  }
  [defs synchronize];
}

 

打印系统所有已注册的字体名称

void enumeratefonts()
{
  for(nsstring *familyname in [uifont familynames])
  {
    nslog(@"%@",familyname);        
    nsarray *fontnames = [uifont fontnamesforfamilyname:familyname];    
    for(nsstring *fontname in fontnames)
    {
      nslog(@"\t|- %@",fontname);
    }
  }
}

获取图片某一点的颜色

- (uicolor*) getpixelcoloratlocation:(cgpoint)point inimage:(uiimage *)image
{

  uicolor* color = nil;
  cgimageref inimage = image.cgimage;
  cgcontextref cgctx = [self createargbbitmapcontextfromimage:inimage];

  if (cgctx == null) {
    return nil; /* error */
  }
  size_t w = cgimagegetwidth(inimage);
  size_t h = cgimagegetheight(inimage);
  cgrect rect = {{0,0},{w,h}};

  cgcontextdrawimage(cgctx, rect, inimage);
  unsigned char* data = cgbitmapcontextgetdata (cgctx);
  if (data != null) {
    int offset = 4*((w*round(point.y))+round(point.x));
    int alpha = data[offset];
    int red = data[offset+1];
    int green = data[offset+2];
    int blue = data[offset+3];
    color = [uicolor colorwithred:(red/255.0f) green:(green/255.0f) blue:
         (blue/255.0f) alpha:(alpha/255.0f)];
  }
  cgcontextrelease(cgctx);
  if (data) {
    free(data);
  }
  return color;
}

字符串反转

//第一种:
- (nsstring *)reversewordsinstring:(nsstring *)str
{  
  nsmutablestring *newstring = [[nsmutablestring alloc] initwithcapacity:str.length];
  for (nsinteger i = str.length - 1; i >= 0 ; i --)
  {
    unichar ch = [str characteratindex:i];    
    [newstring appendformat:@"%c", ch];  
  }  
   return newstring;
}

//第二种:
- (nsstring*)reversewordsinstring:(nsstring*)str
{  
   nsmutablestring *reverstring = [nsmutablestring stringwithcapacity:str.length];  
   [str enumeratesubstringsinrange:nsmakerange(0, str.length) options:nsstringenumerationreverse | nsstringenumerationbycomposedcharactersequences usingblock:^(nsstring *substring, nsrange substringrange, nsrange enclosingrange, bool *stop) { 
     [reverstring appendstring:substring];             
   }];  
   return reverstring;
}

禁止锁屏

//第一种
[uiapplication sharedapplication].idletimerdisabled = yes;
//第二种
[[uiapplication sharedapplication] setidletimerdisabled:yes];

 模态推出透明界面

uiviewcontroller *vc = [[uiviewcontroller alloc] init];
uinavigationcontroller *na = [[uinavigationcontroller alloc] initwithrootviewcontroller:vc];

if ([[[uidevice currentdevice] systemversion] floatvalue] >= 8.0)
{
   na.modalpresentationstyle = uimodalpresentationovercurrentcontext;
}
else
{
   self.modalpresentationstyle=uimodalpresentationcurrentcontext;
}

[self presentviewcontroller:na animated:yes completion:nil];

ios跳转到app store下载应用评分

[[uiapplication sharedapplication] openurl:[nsurl urlwithstring:@"itms-apps://itunes.apple.com/webobjects/mzstore.woa/wa/viewcontentsuserreviews?type=purple+software&id=appid"]];
 

手动更改ios状态栏的颜色

- (void)setstatusbarbackgroundcolor:(uicolor *)color
{
  uiview *statusbar = [[[uiapplication sharedapplication] valueforkey:@"statusbarwindow"] valueforkey:@"statusbar"];

  if ([statusbar respondstoselector:@selector(setbackgroundcolor:)])
  {
    statusbar.backgroundcolor = color;  
  }
}

判断当前viewcontroller是push还是present的方式显示

nsarray *viewcontrollers=self.navigationcontroller.viewcontrollers;

if (viewcontrollers.count > 1)
{
  if ([viewcontrollers objectatindex:viewcontrollers.count - 1] == self)
  {
    //push方式
    [self.navigationcontroller popviewcontrolleranimated:yes];
  }
}
else
{
  //present方式
  [self dismissviewcontrolleranimated:yes completion:nil];
}

 

获取实际使用的launchimage图片

- (nsstring *)getlaunchimagename
{
  cgsize viewsize = self.window.bounds.size;
  // 竖屏  
  nsstring *vieworientation = @"portrait"; 
  nsstring *launchimagename = nil;  
  nsarray* imagesdict = [[[nsbundle mainbundle] infodictionary] valueforkey:@"uilaunchimages"];
  for (nsdictionary* dict in imagesdict)
  {
    cgsize imagesize = cgsizefromstring(dict[@"uilaunchimagesize"]);
    if (cgsizeequaltosize(imagesize, viewsize) && [vieworientation isequaltostring:dict[@"uilaunchimageorientation"]])
    {
      launchimagename = dict[@"uilaunchimagename"];    
    }  
  }  
  return launchimagename;
}

ios在当前屏幕获取第一响应

uiwindow * keywindow = [[uiapplication sharedapplication] keywindow];
uiview * firstresponder = [keywindow performselector:@selector(firstresponder)];
 

判断对象是否遵循了某协议

if ([self.selectedcontroller conformstoprotocol:@protocol(refreshptotocol)])
{
   [self.selectedcontroller performselector:@selector(ontriggerrefresh)];
}
 

判断view是不是指定视图的子视图
bool isview = [textview isdescendantofview:self.view]; 

nsarray 快速求总和 最大值 最小值 和 平均值

nsarray *array = [nsarray arraywithobjects:@"2.0", @"2.3", @"3.0", @"4.0", @"10", nil];
cgfloat sum = [[array valueforkeypath:@"@sum.floatvalue"] floatvalue];
cgfloat avg = [[array valueforkeypath:@"@avg.floatvalue"] floatvalue];
cgfloat max =[[array valueforkeypath:@"@max.floatvalue"] floatvalue];
cgfloat min =[[array valueforkeypath:@"@min.floatvalue"] floatvalue];
nslog(@"%f\n%f\n%f\n%f",sum,avg,max,min);
 

修改uitextfield中placeholder的文字颜色
[textfield setvalue:[uicolor redcolor] forkeypath:@"_placeholderlabel.textcolor"]; 

获取一个类的所有子类

+ (nsarray *) allsubclasses
{
  class myclass = [self class];
  nsmutablearray *mysubclasses = [nsmutablearray array];
  unsigned int numofclasses;
  class *classes = objc_copyclasslist(&numofclasses;);
  for (unsigned int ci = 0; ci < numofclasses; ci++)
  {
    class superclass = classes[ci];
    do{
      superclass = class_getsuperclass(superclass);
    } while (superclass && superclass != myclass);

    if (superclass)
    {
      [mysubclasses addobject: classes[ci]];
    }
  }
  free(classes);
  return mysubclasses;
}

阿拉伯数字转中文格式

+(nsstring *)translation:(nsstring *)arebic
{ 
  nsstring *str = arebic;
  nsarray *arabic_numerals = @[@"1",@"2",@"3",@"4",@"5",@"6",@"7",@"8",@"9",@"0"];
  nsarray *chinese_numerals = @[@"一",@"二",@"三",@"四",@"五",@"六",@"七",@"八",@"九",@"零"];
  nsarray *digits = @[@"个",@"十",@"百",@"千",@"万",@"十",@"百",@"千",@"亿",@"十",@"百",@"千",@"兆"];
  nsdictionary *dictionary = [nsdictionary dictionarywithobjects:chinese_numerals forkeys:arabic_numerals];

  nsmutablearray *sums = [nsmutablearray array];
  for (int i = 0; i < str.length; i ++) {
    nsstring *substr = [str substringwithrange:nsmakerange(i, 1)];
    nsstring *a = [dictionary objectforkey:substr];
    nsstring *b = digits[str.length -i-1];
    nsstring *sum = [a stringbyappendingstring:b];
    if ([a isequaltostring:chinese_numerals[9]])
    {
      if([b isequaltostring:digits[4]] || [b isequaltostring:digits[8]])
      {
        sum = b;
        if ([[sums lastobject] isequaltostring:chinese_numerals[9]])
        {
          [sums removelastobject];
        }
      }else
      {
        sum = chinese_numerals[9];
      }

      if ([[sums lastobject] isequaltostring:sum])
      {
        continue;
      }
    }

    [sums addobject:sum];
  }

  nsstring *sumstr = [sums componentsjoinedbystring:@""];
  nsstring *chinese = [sumstr substringtoindex:sumstr.length-1];
  nslog(@"%@",str);
  nslog(@"%@",chinese);
  return chinese;
}

 

取消uicollectionview的隐式动画

//方法一
[uiview performwithoutanimation:^{
  [collectionview reloaditemsatindexpaths:@[[nsindexpath indexpathforitem:index insection:0]]];
}];

//方法二
[uiview animatewithduration:0 animations:^{
  [collectionview performbatchupdates:^{
    [collectionview reloaditemsatindexpaths:@[[nsindexpath indexpathforitem:index insection:0]]];
  } completion:nil];
}];

//方法三
[uiview setanimationsenabled:no];
[self.trackpanel performbatchupdates:^{
  [collectionview reloaditemsatindexpaths:@[[nsindexpath indexpathforitem:index insection:0]]];
} completion:^(bool finished) {
  [uiview setanimationsenabled:yes];
}];

判断邮箱格式是否正确的代码

-(bool)isvalidateemail:(nsstring *)email

  {

  nsstring *emailregex = @"[a-z0-9a-z._%+-]+@[a-za-z0-9.-]+\\.[a-za-z]{2,4}";

  nspredicate *emailtest = [nspredicate predicatewithformat:@"self matches%@",emailregex];

  return [emailtest evaluatewithobject:email];

  }

ios中uitextfield的字数限制

//在viewdidload中注册<uitextfieldtextdidchangenotification>通知
[[nsnotificationcenter defaultcenter]addobserver:self selector:@selector(textfilededitchanged:) 
     name:@"uitextfieldtextdidchangenotification" object:mytextfield];
//实现监听方法
#pragma mark - notification method
-(void)textfieldeditchanged:(nsnotification *)obj
{
  uitextfield *textfield = (uitextfield *)obj.object;
  nsstring *tobestring = textfield.text;

  //获取高亮部分
  uitextrange *selectedrange = [textfield markedtextrange];
  uitextposition *position = [textfield positionfromposition:selectedrange.start offset:0];

  // 没有高亮选择的字,则对已输入的文字进行字数统计和限制
  if (!position)
  {
    if (tobestring.length > max_starwords_length)
    {
      nsrange rangeindex = [tobestring rangeofcomposedcharactersequenceatindex:max_starwords_length];
      if (rangeindex.length == 1)
      {
        textfield.text = [tobestring substringtoindex:max_starwords_length];
      }
      else
      {
        nsrange rangerange = [tobestring rangeofcomposedcharactersequencesforrange:nsmakerange(0, max_starwords_length)];
        textfield.text = [tobestring substringwithrange:rangerange];
      }
    }
  }
}

小伙伴们,今天就分享到这里,下期更精彩!

上一篇:

下一篇: