服务器之家:专注于服务器技术及软件下载分享
分类导航

PHP教程|ASP.NET教程|Java教程|ASP教程|编程技术|正则表达式|C/C++|IOS|C#|Swift|Android|VB|R语言|JavaScript|易语言|vb.net|

服务器之家 - 编程语言 - IOS - 值得收藏的iOS开发常用代码块

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

2021-02-03 15:24tylerzhang IOS

这篇文章主要为大家详细介绍了iOS开发常用代码块,具有一定的参考价值,感兴趣的小伙伴们可以参考一下

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

?
1
2
3
4
5
6
7
NSMutableArray *copyArray = [NSMutableArray arrayWithArray:array]; 
NSString *str1 = @“zhangsan”;
for (AddressPerson *perName in copyArray) {
  if ([[perName name] isEqualToString:str1]) {
    [array removeObject:perName];
  }
}

获取系统当前语言

?
1
2
3
4
5
6
7
8
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样式下顶部空白处理

?
1
2
UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 0, 0.1)];
self.tableView.tableHeaderView = view;

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

?
1
2
3
4
5
6
7
8
9
10
11
12
- (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所在的控制器

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
- (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所有记录

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
//方法一
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];
}
 

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

?
1
2
3
4
5
6
7
8
9
10
11
12
void enumerateFonts()
{
  for(NSString *familyName in [UIFont familyNames])
  {
    NSLog(@"%@",familyName);       
    NSArray *fontNames = [UIFont fontNamesForFamilyName:familyName];   
    for(NSString *fontName in fontNames)
    {
      NSLog(@"\t|- %@",fontName);
    }
  }
}

获取图片某一点的颜色

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
- (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;
}

字符串反转

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
//第一种:
- (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;
}

禁止锁屏

?
1
2
3
4
//第一种
[UIApplication sharedApplication].idleTimerDisabled = YES;
//第二种
[[UIApplication sharedApplication] setIdleTimerDisabled:YES];

 模态推出透明界面

?
1
2
3
4
5
6
7
8
9
10
11
12
13
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下载应用评分

?
1
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"itms-apps://itunes.apple.com/WebObjects/MZStore.woa/wa/viewContentsUserReviews?type=Purple+Software&id=APPID"]];
 

手动更改iOS状态栏的颜色

?
1
2
3
4
5
6
7
8
9
- (void)setStatusBarBackgroundColor:(UIColor *)color
{
  UIView *statusBar = [[[UIApplication sharedApplication] valueForKey:@"statusBarWindow"] valueForKey:@"statusBar"];
 
  if ([statusBar respondsToSelector:@selector(setBackgroundColor:)])
  {
    statusBar.backgroundColor = color; 
  }
}

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

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
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图片

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
- (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在当前屏幕获取第一响应

?
1
2
UIWindow * keyWindow = [[UIApplication sharedApplication] keyWindow];
UIView * firstResponder = [keyWindow performSelector:@selector(firstResponder)];
 

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

?
1
2
3
4
if ([self.selectedController conformsToProtocol:@protocol(RefreshPtotocol)])
{
   [self.selectedController performSelector:@selector(onTriggerRefresh)];
}
 

判断view是不是指定视图的子视图
BOOL isView = [textView isDescendantOfView:self.view]; 

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

?
1
2
3
4
5
6
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"]; 

获取一个类的所有子类

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
+ (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;
}

阿拉伯数字转中文格式

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
+(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的隐式动画

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
//方法一
[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];
}];

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

?
1
2
3
4
5
6
7
8
9
10
11
-(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的字数限制

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
//在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];
      }
    }
  }
}

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

延伸 · 阅读

精彩推荐
  • IOSiOS 雷达效果实例详解

    iOS 雷达效果实例详解

    这篇文章主要介绍了iOS 雷达效果实例详解的相关资料,需要的朋友可以参考下...

    SimpleWorld11022021-01-28
  • IOSIOS开发之字典转字符串的实例详解

    IOS开发之字典转字符串的实例详解

    这篇文章主要介绍了IOS开发之字典转字符串的实例详解的相关资料,希望通过本文能帮助到大家,让大家掌握这样的方法,需要的朋友可以参考下...

    苦练内功5832021-04-01
  • IOSiOS中tableview 两级cell的展开与收回的示例代码

    iOS中tableview 两级cell的展开与收回的示例代码

    本篇文章主要介绍了iOS中tableview 两级cell的展开与收回的示例代码,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧...

    J_Kang3862021-04-22
  • IOS解析iOS开发中的FirstResponder第一响应对象

    解析iOS开发中的FirstResponder第一响应对象

    这篇文章主要介绍了解析iOS开发中的FirstResponder第一响应对象,包括View的FirstResponder的释放问题,需要的朋友可以参考下...

    一片枫叶4662020-12-25
  • IOSiOS布局渲染之UIView方法的调用时机详解

    iOS布局渲染之UIView方法的调用时机详解

    在你刚开始开发 iOS 应用时,最难避免或者是调试的就是和布局相关的问题,下面这篇文章主要给大家介绍了关于iOS布局渲染之UIView方法调用时机的相关资料...

    windtersharp7642021-05-04
  • IOSiOS通过逆向理解Block的内存模型

    iOS通过逆向理解Block的内存模型

    自从对 iOS 的逆向初窥门径后,我也经常通过它来分析一些比较大的应用,参考一下这些应用中某些功能的实现。这个探索的过程乐趣多多,不仅能满足自...

    Swiftyper12832021-03-03
  • IOS关于iOS自适应cell行高的那些事儿

    关于iOS自适应cell行高的那些事儿

    这篇文章主要给大家介绍了关于iOS自适应cell行高的那些事儿,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的...

    daisy6092021-05-17
  • IOSIOS 屏幕适配方案实现缩放window的示例代码

    IOS 屏幕适配方案实现缩放window的示例代码

    这篇文章主要介绍了IOS 屏幕适配方案实现缩放window的示例代码,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要...

    xiari5772021-06-01