JoanKing常用代码(下)

简介: JoanKing常用代码(下)

26.两种跳转展示


  • 1.中间展示(两种写法)


image.png

//第一种方法
  1.挂代理<UIActionSheetDelegate>
  2.在点击的地方调用
  UIAlertView * alertView = [[UIAlertView alloc]initWithTitle:@"全国统一客服热线4007-114-115" message:nil delegate:self cancelButtonTitle:@"拨打" otherButtonTitles:@"取消", nil];
  [alertView show];
  3.方法调用
  - (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex 
 {
      if (buttonIndex == 0)
     {
          NSLog(@"拨打");
     }else if (buttonIndex == 1)
     {
           NSLog(@"取消");
     }  
 }
//第二种方法(方法里面直接调用:不用挂代理)
UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"全国统一客服热线4007-114-115" message:nil preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction *alertAction = [UIAlertAction actionWithTitle:@"拨打" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
    NSLog(@"拨打");
}];
UIAlertAction *alertAction2 = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
     NSLog(@"取消");
}];
[alertController addAction:alertAction];
[alertController addAction:alertAction2];
[self presentViewController:alertController animated:YES completion:nil];


  • 2.下面展示

image.png

//第一种方法
1.第一种挂代理<UIActionSheetDelegate>
2.在点击的地方调用
UIActionSheet *sheet = [[UIActionSheet alloc] initWithTitle:nil delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"从手机选择", @"拍照", nil];
sheet.actionSheetStyle = UIBarStyleDefault;
[sheet showInView:self.view];
3.方法调用
 -(void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
 {
     if (buttonIndex == 0)
    {
           NSLog(@"我是从手机选择");
    }else if (buttonIndex == 1)
    {
           NSLog(@"我是拍照");
    }
 }
 //第二种方法(方法里面直接调用:不用挂代理)
  UIAlertController *alertController = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
UIAlertAction *alertAction = [UIAlertAction actionWithTitle:@"从手机选择" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
    NSLog(@"从手机选择");
}];
UIAlertAction *alertAction1 = [UIAlertAction actionWithTitle:@"拍照" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
     NSLog(@"拍照");
}];
UIAlertAction *alertAction2 = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
    NSLog(@"取消");
}];
[alertController addAction:alertAction];
[alertController addAction:alertAction1];
[alertController addAction:alertAction2];
[self presentViewController:alertController animated:YES completion:nil];

27.对控件边框的处理(如宽度,颜色)

对象(button,label...).layer.borderColor = [[UIColor blackColor] CGColor];
对象(button,label...).layer.borderWidth = 2.0f;

28.自定义导航栏标题

UILabel *titleLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, 100, 44)];
titleLabel.text = @"登陆";
titleLabel.textAlignment = NSTextAlignmentCenter;
titleLabel.textColor = [UIColor blackColor];
titleLabel.font = [UIFont systemFontOfSize:15];
self.navigationItem.titleView = titleLabel;

29.静态变量的含义


static 表示只在此文件里可以访问(防止其他文件访问) const防止别人去改

static NSString *const ID = @"cellID";

30.懒加载的一些知识点


懒加载里面都是用_,但是在外面使用都要用self.  这样才能保证数据的存在性


31.切换UICollectionViewFolowLayout


CwLineLayout 是自定义的layout

if ([self.collectionView.collectionViewLayout isKindOfClass:[CwLineLayout class]]) {
    [self.collectionView setCollectionViewLayout:[[UICollectionViewFlowLayout alloc]init] animated:YES];
}else
{
    [self.collectionView setCollectionViewLayout:[[CwLineLayout alloc]init] animated:YES];
}

31.删除指定item

/**
  *  collectionView的点击事件
  */
 -(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
  //删除模型数据(删除的指定item)
  [self.imageArray removeObjectAtIndex:indexPath.item];
  //刷新UI(这种方式比全局的好很多)
  [collectionView deleteItemsAtIndexPaths:@[indexPath]];
 }

32.textField.returnKeyType = UIReturnKeySend;

typedef NS_ENUM(NSInteger, UIReturnKeyType) {

UIReturnKeyDefault,
UIReturnKeyGo,//去往
UIReturnKeyGoogle,
UIReturnKeyJoin,//加入
UIReturnKeyNext,//下一步
UIReturnKeyRoute,
UIReturnKeySearch,//搜索
UIReturnKeySend,//发送
UIReturnKeyYahoo,
UIReturnKeyDone,//完成
UIReturnKeyEmergencyCall,
UIReturnKeyContinue NS_ENUM_AVAILABLE_IOS(9_0),
};

33.下一个tabBar隐藏

testViewController.hidesBottomBarWhenPushed = YES;

34. 判断手机号码格式是否正确,利用正则表达式验证

+ (BOOL)isMobileNumber:(NSString *)mobileNum
{
   if (mobileNum.length != 11)
    {
        return NO; 
    }
    /** * 手机号码:
     * 13[0-9], 14[5,7], 15[0, 1, 2, 3, 5, 6, 7, 8, 9], 17[6, 7, 8], 18[0-9], 170[0-9] 
     * 移动号段: 134,135,136,137,138,139,150,151,152,157,158,159,182,183,184,187,188,147,178,1705 
     * 联通号段: 130,131,132,155,156,185,186,145,176,1709 
     * 电信号段: 133,153,180,181,189,177,1700 
     */ 
     NSString *MOBILE = @"^1(3[0-9]|4[57]|5[0-35-9]|8[0-9]|70)\d{8}$";
     /** * 中国移动:China Mobile 
      * 134,135,136,137,138,139,150,151,152,157,158,159,182,183,184,187,188,147,178,1705
      */ 
      NSString *CM = @"(^1(3[4-9]|4[7]|5[0-27-9]|7[8]|8[2-478])\d{8}$)|(^1705\d{7}$)"; 
      /** * 中国联通:China Unicom
       * 130,131,132,155,156,185,186,145,176,1709 
       */
       NSString *CU = @"(^1(3[0-2]|4[5]|5[56]|7[6]|8[56])\d{8}$)|(^1709\d{7}$)"; 
       /** * 中国电信:China Telecom
        * 133,153,180,181,189,177,1700 
        */
       NSString *CT = @"(^1(33|53|77|8[019])\d{8}$)|(^1700\d{7}$)"; 
       NSPredicate *regextestmobile = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", MOBILE]; 
       NSPredicate *regextestcm = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CM]; 
       NSPredicate *regextestcu = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CU]; 
       NSPredicate *regextestct = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CT]; 
      if (([regextestmobile evaluateWithObject:mobileNum] == YES) || ([regextestcm evaluateWithObject:mobileNum] == YES) || ([regextestct evaluateWithObject:mobileNum] == YES) || ([regextestcu evaluateWithObject:mobileNum] == YES))
       {
           return YES; 
       } 
       else
       { 
           return NO;
       }
  }

35. 判断邮箱格式是否正确,利用正则表达式验证

+ (BOOL)isAvailableEmail:(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];
 }

36. 判断字符串中是否含有空格

+ (BOOL)isHaveSpaceInString:(NSString *)string
 {
    NSRange _range = [string rangeOfString:@" "]; 
    if (_range.location != NSNotFound) 
    { 
       return YES; 
    }else
    { 
        return NO; 
    }
  }

37. 判断字符串中是否含有中文

+ (BOOL)isHaveChineseInString:(NSString *)string
   { 
      for(NSInteger i = 0; i < [string length]; i++)
      { 
           int a = [string characterAtIndex:i];
           if (a > 0x4e00 && a < 0x9fff) 
           {
                return YES;
           } 
      } 
       return NO;
    }

38. 判断字符串是否全部为数字

+ (BOOL)isAllNum:(NSString *)string
   {
      unichar c;
      for (int i=0; i<string.length; i++) {         c="[string characterAtIndex:i];"         if (!isdigit(c)) {=""             return no;=""         }=""     }=""     return yes;="" }<="" pre=""><p>判断是否是纯数字</p><pre class="brush:js;toolbar:false">+ (BOOL)isPureInteger:(NSString *)str {
      NSScanner *scanner = [NSScanner scannerWithString:str];
      NSInteger val;
      return [scanner scanInteger:&val] && [scanner isAtEnd];
   }

39. 过滤一些特殊字符 似乎只能去除头尾的特殊字符(不准)

+ (NSString *)filterSpecialWithString:(NSString *)string
{
     // 定义一个特殊字符的集合 
     NSCharacterSet *set = [NSCharacterSet characterSetWithCharactersInString: @ "@/:;: ;()?「」"、[]{}#%-*+=_|~<>$?^?'@#$%^&*()_+'"]; 
     // 过滤字符串的特殊字符 
    NSString *newString = [string stringByTrimmingCharactersInSet:set]; return newString;
}

40. 让iOS应用直接退出

+ (void)backOutApp 
 { 
     UIWindow *window = [[UIApplication sharedApplication].delegate window];
     [UIView animateWithDuration:1.0f animations:^{
        window.alpha = 0; 
      } completion:^(BOOL finished) 
      {
         exit(0); 
      }];
  }

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

+ (NSString *)caculateArray:(NSArray *)array
{ 
   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(@"%fn%fn%fn%f",sum,avg,max,min); 
   return [NSString stringWithFormat:@"%f",sum];
}

42.生成八位随机字符串(一般是RSA加密或者DES加密使用)

- (NSString *)shuffledAlphabet {
NSString *alphabet = @"ABCDEFGHIJKLMNOPQRSTUVWXYZ";
// Get the characters into a C array for efficient shuffling
NSUInteger numberOfCharacters = [alphabet length];
unichar *characters = calloc(numberOfCharacters, sizeof(unichar));
[alphabet getCharacters:characters range:NSMakeRange(0, numberOfCharacters)];
// Perform a Fisher-Yates shuffle
for (NSUInteger i = 0; i < numberOfCharacters; ++i) {
    NSUInteger j = (arc4random_uniform((float)numberOfCharacters - i) + i);
    unichar c = characters[i];
    characters[i] = characters[j];
    characters[j] = c;
}
   // Turn the result back into a string
   NSString *result = [NSString stringWithCharacters:characters length:8];
free(characters);
   return result;
}

43.判断是真机还是模拟器

#if TARGET_OS_IPHONE
   //iPhone Device
   #endif
   #if TARGET_IPHONE_SIMULATOR
   //iPhone Simulator
   #endif

44.GCD 的宏定义


很多小伙伴都非常烦写GCD的方法,所以在此定义为宏使用更加方便简洁!如下图


image.png


//GCD - 一次性执行
#define kDISPATCH_ONCE_BLOCK(onceBlock) static dispatch_once_t onceToken; dispatch_once(&onceToken, onceBlock);
//GCD - 在Main线程上运行
#define kDISPATCH_MAIN_THREAD(mainQueueBlock) dispatch_async(dispatch_get_main_queue(), mainQueueBlock);
//GCD - 开启异步线程
#define kDISPATCH_GLOBAL_QUEUE_DEFAULT(globalQueueBlock) dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), globalQueueBlocl);

45.判断当前的iPhone设备/系统版本

//判断是否为iPhone
#define IS_IPHONE (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone)
//判断是否为iPad
#define IS_IPAD (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
//判断是否为ipod
#define IS_IPOD ([[[UIDevice currentDevice] model] isEqualToString:@"iPod touch"])
// 判断是否为 iPhone 5SE
#define iPhone5SE [[UIScreen mainScreen] bounds].size.width == 320.0f && [[UIScreen mainScreen] bounds].size.height == 568.0f
// 判断是否为iPhone 6/6s
#define iPhone6_6s [[UIScreen mainScreen] bounds].size.width == 375.0f && [[UIScreen mainScreen] bounds].size.height == 667.0f
// 判断是否为iPhone 6Plus/6sPlus
#define iPhone6Plus_6sPlus [[UIScreen mainScreen] bounds].size.width == 414.0f && [[UIScreen mainScreen] bounds].size.height == 736.0f
//获取系统版本
#define IOS_SYSTEM_VERSION [[[UIDevice currentDevice] systemVersion] floatValue]
//判断 iOS 8 或更高的系统版本
#define IOS_VERSION_8_OR_LATER (([[[UIDevice currentDevice] systemVersion] floatValue] >=8.0)? (YES):(NO))

46.获取当前语言

#define LRCurrentLanguage ([[NSLocale preferredLanguages] objectAtIndex:0])

47.“Info.plist”中将要使用的URL Schemes列为白名单

当你的应用在iOS 9中需要使用 QQ/QQ空间/支付宝/微信SDK 的相关能力(分享、收藏、支付、登录等)时,需要在“Info.plist”里增加如下代码:

<key>LSApplicationQueriesSchemes</key>
<array>
<!-- 微信 URL Scheme 白名单-->
<string>wechat</string>
<string>weixin</string>
<!-- 新浪微博 URL Scheme 白名单-->
<string>sinaweibohd</string>
<string>sinaweibo</string>
<string>sinaweibosso</string>
<string>weibosdk</string>
<string>weibosdk2.5</string>
<!-- QQ、Qzone URL Scheme 白名单-->
<string>mqqapi</string>
<string>mqq</string>
<string>mqqOpensdkSSoLogin</string>
<string>mqqconnect</string>
<string>mqqopensdkdataline</string>
<string>mqqopensdkgrouptribeshare</string>
<string>mqqopensdkfriend</string>
<string>mqqopensdkapi</string>
<string>mqqopensdkapiV2</string>
<string>mqqopensdkapiV3</string>
<string>mqzoneopensdk</string>
<string>wtloginmqq</string>
<string>wtloginmqq2</string>
<string>mqqwpa</string>
<string>mqzone</string>
<string>mqzonev2</string>
<string>mqzoneshare</string>
<string>wtloginqzone</string>
<string>mqzonewx</string>
<string>mqzoneopensdkapiV2</string>
<string>mqzoneopensdkapi19</string>
<string>mqzoneopensdkapi</string>
<string>mqzoneopensdk</string>
<!-- 支付宝  URL Scheme 白名单-->
<string>alipay</string>
<string>alipayshare</string>
</array>

48.将秒转化为时间字符串

秒数
float currentPlayTime = 64;
//将秒转化为时间字符串
NSString *currentTimeStr =  [self convertDuraion:currentPlayTime];
- (NSString *)convertDuraion:(float)duraion{
    NSDate *date = [NSDate dateWithTimeIntervalSince1970:duraion];
    NSDateFormatter *dateFormate = [[NSDateFormatter alloc]init];
    dateFormate.dateFormat = @"mm:ss";
    return [dateFormate stringFromDate:date];
}

49.有关字符串

NSString *string1 = @"0123456789";
  NSRange range1 = NSMakeRange(1, 4);//NSMakeRange这个函数的作用是从第0位开始计算,长度为4
  NSLog(@"从第1个字符开始,长度为4的字符串是:%@",[string1 substringWithRange:range1]);
  NSLog(@"抽取从头开始到第4个字符:%@",[string1 substringToIndex:4]);
  NSLog(@"抽取从第6个字符开始到末尾:%@",[string1 substringFromIndex:6]);
  NSString *string2 = @"wo shi xiao bai zhu";
  NSRange range2 = [string2 rangeOfString:@"bai"];
  if (range2.length > 0) {
       NSLog(@"{字符串中“bai”的位置,长度}==%@",NSStringFromRange(range2));
   }
   //判断在一串字符串中是否找到某个字符串
   NSRange range3 = [string2 rangeOfString:@"zhu"];
  if (range3.location != NSNotFound) {
      NSLog(@"找到了@“zhu”这个字符串!");
  }
  else
  {
     NSLog(@"没找到!");
  }

50.交换两个值(异或)


image.png


51.角度转弧度

宏定义: #define angle2radion(angle)  ((angle) / 180.0 * M_PI)

52.获取当前的系统时间(以日历表为例)

//获取当前日历对象
NSCalendar  *calendar =[NSCalendar currentCalendar];
//获取日期的组件,年月日,时分秒
//components: 需要获取日期组件
//formDate:获取哪个日期组件
//经验:以后枚举中有移位运算符(<<),一般来说我们就可以用 |  :"并" 的方式
NSDateComponents  *dateComponents = [calendar components:NSCalendarUnitSecond | NSCalendarUnitMinute | NSCalendarUnitHour | NSCalendarUnitDay | NSCalendarUnitMonth | NSCalendarUnitYear fromDate:[NSDate date]];
NSLog(@"小时==%ld",dateComponents.hour);
NSLog(@"分钟==%ld",dateComponents.minute);
NSLog(@"秒==%ld",dateComponents.second);

53.点转化为对象

[NSValue valueWithCGPoint:CGPointMake(arc4random_uniform(500), arc4random_uniform(500))];

54.隐藏tabBar

控制器对象.hidesBottomBarWhenPushed = YES;(比较好)

55.刷新指定section或者row

//一个section刷新
NSIndexSet *indexSet=[[NSIndexSet alloc]initWithIndex:indexPath.section];
[_tableView reloadSections:indexSet withRowAnimation:UITableViewRowAnimationAutomatic];
//一个cell刷新
NSIndexPath *indexPath1=[NSIndexPath indexPathForRow:3 inSection:0];
[tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath1,nil] withRowAnimation:UITableViewRowAnimationNone];

56.  遍历字典

NSDictionary *dict = [NSDictionary new];
[dict enumerateKeysAndObjectsUsingBlock:^(id  _Nonnull key, id  _Nonnull obj, BOOL * _Nonnull stop) {
    // key 是键
    // obj 是值
}];

57.   NSTimer定时器

创建定时器
NSTimer * timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(click1) userInfo:nil repeats:YES];
暂停
    [timer setFireDate:[NSDate distantFuture]];
继续
    [timer setFireDate:[NSDate date]];
关闭定时器
    [timer invalidate];

58.两张图片的合成

/**
 *  3.将两个图片合成
 */
dispatch_group_notify(group, queue, ^{
    /**
     *  开启新的图形上下文
     */
    UIGraphicsBeginImageContext(CGSizeMake(200, 200));
    //绘制图片
    [self.image1 drawInRect:CGRectMake(0, 0, 200, 100)];
    //绘制图片
    [self.image2 drawInRect:CGRectMake(0, 100, 200, 100)];
    /**
     *  取得上下文里面的图片
     */
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    /**
     *  结束上下文
     */
    UIGraphicsEndImageContext();
    /**
     *  4.进入主队列加载合成的图片
     */
    dispatch_async(dispatch_get_main_queue(), ^{
        self.imageView.image = image;
    });
59沙盒路径

//获取整个程序所在目录
NSString *homePath=NSHomeDirectory();
NSLog(@"%@",homePath);
//获取.app文件目录
NSString *appPath=[[NSBundle mainBundle]bundlePath];
NSLog(@"%@",appPath);
//Documents目录
NSArray *arr1=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSLog(@"%@",[arr1 objectAtIndex:0]);
//Library目录
NSArray *arr2=NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES);
NSLog(@"%@",[arr2 objectAtIndex:0]);
//Caches目录,在Library下面
NSArray *arr3=NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
NSLog(@"%@",[arr3 objectAtIndex:0]);
//tmp目录
NSString *tmpPath=NSTemporaryDirectory();
NSLog(@"%@",tmpPath);
//用整个程序目录加上tmp就拼凑出tmp目录,其他目录都可这样完成
NSString *tmpPath_1=[homePath stringByAppendingPathComponent:@"tmp"];
NSLog(@"%@",tmpPath_1);

60.几个常用的正则表达式

//邮箱
  + (BOOL) validateEmail:(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];
  }
 //手机号码验证
 + (BOOL) validateMobile:(NSString *)mobile
 {
     //手机号以13, 15,18开头,八个 \d 数字字符
     NSString *phoneRegex = @"^((13[0-9])|(15[^4,\\D])|(18[0,0-9]))\\d{8}$";
     NSPredicate *phoneTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",phoneRegex];
     return [phoneTest evaluateWithObject:mobile];
}
//车牌号验证
+ (BOOL) validateCarNo:(NSString *)carNo
{
    NSString *carRegex = @"^[\u4e00-\u9fa5]{1}[a-zA-Z]{1}[a-zA-Z_0-9]{4}[a-zA-Z_0-9_\u4e00-\u9fa5]$";
    NSPredicate *carTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",carRegex];
    NSLog(@"carTest is %@",carTest);
    return [carTest evaluateWithObject:carNo];
 }
//车型
+ (BOOL) validateCarType:(NSString *)CarType
{
    NSString *CarTypeRegex = @"^[\u4E00-\u9FFF]+$";
    NSPredicate *carTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",CarTypeRegex];
    return [carTest evaluateWithObject:CarType];
}
//用户名
+ (BOOL) validateUserName:(NSString *)name
{
   NSString *userNameRegex = @"^[A-Za-z0-9]{6,20}+$";
   NSPredicate *userNamePredicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",userNameRegex];
   BOOL B = [userNamePredicate evaluateWithObject:name];
   return B;
}
//密码
+ (BOOL) validatePassword:(NSString *)passWord
{
   NSString *passWordRegex = @"^[a-zA-Z0-9]{6,20}+$";
   NSPredicate *passWordPredicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",passWordRegex];
   return [passWordPredicate evaluateWithObject:passWord];
}
 //以下验证不计算长度
 //1、验证字符串
 - (BOOL)validateNickname:(NSString *)nickname {
     // 不包含特殊字符
    // 特殊字符包含`、-、=、\、[、]、;、'、,、.、/、~、!、@、#、$、%、^、&、*、(、)、_、+、|、?、>、<、"、:、{、}
    NSString *nicknameRegex = @".*[-`=\\\[\\];',./~!@#$%^&*()_+|{}:\"<>?]+.*";
    NSPredicate *nicknamePredicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", nicknameRegex];
    return ![nicknamePredicate evaluateWithObject:nickname];
}
 //2、验证密码
 - (BOOL)validatePassword:(NSString *)password {
    // 特殊字符包含`、-、=、\、[、]、;、'、,、.、/、~、!、@、#、$、%、^、&、*、(、)、_、+、|、?、>、<、"、:、{、}
    // 必须包含数字和字母,可以包含上述特殊字符。
    // 依次为(如果包含特殊字符)
    // 数字 字母 特殊
    // 字母 数字 特殊
    // 数字 特殊 字母
    // 字母 特殊 数字
    // 特殊 数字 字母
    // 特殊 字母 数字
     NSString *passWordRegex = @"(\\d+[a-zA-Z]+[-`=\\\[\\];',./~!@#$%^&*()_+|{}:\"<>?]*)|([a-zA-Z]+\\d+[-`=\\\[\\];',./~!@#$%^&*()_+|{}:\"<>?]*)|(\\d+[-`=\\\[\\];',./~!@#$%^&*()_+|{}:\"<>?]*[a-zA-Z]+)|([a-zA-Z]+[-`=\\\[\\];',./~!@#$%^&*()_+|{}:\"<>?]*\\d+)|([-`=\\\[\\];',./~!@#$%^&*()_+|{}:\"<>?]*\\d+[a-zA-Z]+)|([-`=\\\[\\];',./~!@#$%^&*()_+|{}:\"<>?]*[a-zA-Z]+\\d+)";
     NSPredicate *passWordPredicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", passWordRegex];
     return [passWordPredicate evaluateWithObject:password];
 }
//昵称
+ (BOOL) validateNickname:(NSString *)nickname
{
   NSString *nicknameRegex = @"^[\u4e00-\u9fa5]{4,8}$";
   NSPredicate *passWordPredicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",nicknameRegex];
   return [passWordPredicate evaluateWithObject:nickname];
}
 //身份证号
  + (BOOL) validateIdentityCard: (NSString *)identityCard
  {
       BOOL flag;
       if (identityCard.length <= 0) {
           flag = NO;
            return flag;
       }
       NSString *regex2 = @"^(\\d{14}|\\d{17})(\\d|[xX])$";
       NSPredicate *identityCardPredicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",regex2];
      return [identityCardPredicate evaluateWithObject:identityCard];
 }

61.打印方式

NSLog(@"控制器名字=%s 第%d行",__PRETTY_FUNCTION__, __LINE__);

62.控制屏幕旋转,在控制器中写

/** 是否支持自动转屏 */
- (BOOL)shouldAutorotate {
    return YES;
}
/** 支持哪些屏幕方向 */
- (UIInterfaceOrientationMask)supportedInterfaceOrientations {
   return UIInterfaceOrientationMaskLandscapeLeft | UIInterfaceOrientationMaskLandscapeRight;
}
/** 默认的屏幕方向(当前ViewController必须是通过模态出来的UIViewController(模态带导航的无效)方式展现出来的,才会调用这个方法) */
- (UIInterfaceOrientation)preferredInterfaceOrientationForPresentation {
    return UIInterfaceOrientationLandscapeLeft | UIInterfaceOrientationLandscapeRight;
}

63.几个常用权限判断

if ([CLLocationManager authorizationStatus] ==kCLAuthorizationStatusDenied) {
    NSLog(@"没有定位权限");
}
AVAuthorizationStatus statusVideo = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
if (statusVideo == AVAuthorizationStatusDenied) {
    NSLog(@"没有摄像头权限");
}
//是否有麦克风权限
AVAuthorizationStatus statusAudio = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeAudio];
if (statusAudio == AVAuthorizationStatusDenied) {
    NSLog(@"没有录音权限");
}
[PHPhotoLibrary requestAuthorization:^(PHAuthorizationStatus status) {
    if (status == PHAuthorizationStatusDenied) {
        NSLog(@"没有相册权限");
    }
}];

64.获取手机和app信息

NSDictionary *infoDictionary = [[NSBundle mainBundle] infoDictionary];  
 CFShow(infoDictionary);  
 // app名称  
 NSString *app_Name = [infoDictionary objectForKey:@"CFBundleDisplayName"];  
 // app版本  
 NSString *app_Version = [infoDictionary objectForKey:@"CFBundleShortVersionString"];  
 // app build版本  
 NSString *app_build = [infoDictionary objectForKey:@"CFBundleVersion"];  
//手机序列号  
NSString* identifierNumber = [[UIDevice currentDevice] uniqueIdentifier];  
NSLog(@"手机序列号: %@",identifierNumber);  
//手机别名: 用户定义的名称  
NSString* userPhoneName = [[UIDevice currentDevice] name];  
NSLog(@"手机别名: %@", userPhoneName);  
//设备名称  
NSString* deviceName = [[UIDevice currentDevice] systemName];  
NSLog(@"设备名称: %@",deviceName );  
//手机系统版本  
NSString* phoneVersion = [[UIDevice currentDevice] systemVersion];  
NSLog(@"手机系统版本: %@", phoneVersion);  
//手机型号  
NSString* phoneModel = [[UIDevice currentDevice] model];  
NSLog(@"手机型号: %@",phoneModel );  
//地方型号  (国际化区域名称)  
NSString* localPhoneModel = [[UIDevice currentDevice] localizedModel];  
NSLog(@"国际化区域名称: %@",localPhoneModel );  
NSDictionary *infoDictionary = [[NSBundle mainBundle] infoDictionary];  
// 当前应用名称  
NSString *appCurName = [infoDictionary objectForKey:@"CFBundleDisplayName"];  
NSLog(@"当前应用名称:%@",appCurName);  
// 当前应用软件版本  比如:1.0.1  
NSString *appCurVersion = [infoDictionary objectForKey:@"CFBundleShortVersionString"];  
NSLog(@"当前应用软件版本:%@",appCurVersion);  
// 当前应用版本号码   int类型  
NSString *appCurVersionNum = [infoDictionary objectForKey:@"CFBundleVersion"];  
NSLog(@"当前应用版本号码:%@",appCurVersionNum);

65.移除字符串中的空格和换行

+ (NSString *)removeSpaceAndNewline:(NSString *)str {
     NSString *temp = [str stringByReplacingOccurrencesOfString:@" " withString:@""];
     temp = [temp stringByReplacingOccurrencesOfString:@"\r" withString:@""];
     temp = [temp stringByReplacingOccurrencesOfString:@"\n" withString:@""];
     return temp;
 }

66.判断字符串中是否有空格

+ (BOOL)isBlank:(NSString *)str {
    NSRange _range = [str rangeOfString:@" "];
    if (_range.location != NSNotFound) {
       //有空格
       return YES;
    } else {
      //没有空格
       return NO;
    }
}

67.获取一个视频的第一帧图片

NSURL *url = [NSURL URLWithString:filepath];
AVURLAsset *asset1 = [[AVURLAsset alloc] initWithURL:url options:nil];
AVAssetImageGenerator *generate1 = [[AVAssetImageGenerator alloc] initWithAsset:asset1];
generate1.appliesPreferredTrackTransform = YES;
NSError *err = NULL;
CMTime time = CMTimeMake(1, 2);
CGImageRef oneRef = [generate1 copyCGImageAtTime:time actualTime:NULL error:&err];
UIImage *one = [[UIImage alloc] initWithCGImage:oneRef];
return one;

68.获取视频的时长

+ (NSInteger)getVideoTimeByUrlString:(NSString *)urlString {
   NSURL *videoUrl = [NSURL URLWithString:urlString];
   AVURLAsset *avUrl = [AVURLAsset assetWithURL:videoUrl];
   CMTime time = [avUrl duration];
   int seconds = ceil(time.value/time.timescale);
   return seconds;
}

69.isKindOfClass和isMemberOfClass的区别

isKindOfClass可以判断某个对象是否属于某个类,或者这个类的子类。
isMemberOfClass更加精准,它只能判断这个对象类型是否为这个类(不能判断子类)

70.将tableView滚动到顶部

[tableView setContentOffset:CGPointZero animated:YES];
或者
[tableView scrollRectToVisible:CGRectMake(0, 0, 1, 1) animated:YES];

71.UILabel设置内边距

子类化UILabel,重写drawTextInRect方法
- (void)drawTextInRect:(CGRect)rect {
// 边距,上左下右
  UIEdgeInsets insets = {0, 5, 0, 5};
  [super drawTextInRect:UIEdgeInsetsInsetRect(rect, insets)];
 }

72.UILabel设置文字描边

子类化UILabel,重写drawTextInRect方法
- (void)drawTextInRect:(CGRect)rect
{
CGContextRef c = UIGraphicsGetCurrentContext();
// 设置描边宽度
CGContextSetLineWidth(c, 1);
CGContextSetLineJoin(c, kCGLineJoinRound);
CGContextSetTextDrawingMode(c, kCGTextStroke);
// 描边颜色
self.textColor = [UIColor redColor];
[super drawTextInRect:rect];
// 文本颜色
self.textColor = [UIColor yellowColor];
CGContextSetTextDrawingMode(c, kCGTextFill);
[super drawTextInRect:rect];
}

73.scrollView滚动到最下边

CGPoint bottomOffset = CGPointMake(0, scrollView.contentSize.height - scrollView.bounds.size.height);
[scrollView setContentOffset:bottomOffset animated:YES];

74.UIView背景颜色渐变

UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 100)];
[self.view addSubview:view];
CAGradientLayer *gradient = [CAGradientLayer layer];
gradient.frame = view.bounds;
gradient.colors = [NSArray arrayWithObjects:(id)[[UIColor blackColor] CGColor], (id)[[UIColor whiteColor] CGColor], nil];
[view.layer insertSublayer:gradient atIndex:0];

75.将一个view放置在其兄弟视图的最上面

[parentView bringSubviewToFront:yourView]

76.将一个view放置在其兄弟视图的最下面

[parentView sendSubviewToBack:yourView]

77.让手机震动一下

倒入框架
#import 
AudioServicesPlayAlertSound(kSystemSoundID_Vibrate);
或者
AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);

78.layoutSubviews方法什么时候调用?

1、init方法不会调用
 2、addSubview方法等时候会调用
 3、bounds改变的时候调用
 4、scrollView滚动的时候会调用scrollView的    
    layoutSubviews方法(所以不建议在scrollView的layoutSubviews方法中做复杂逻辑)
 5、旋转设备的时候调用
 6、子视图被移除的时候调用

79.让UILabel在指定的地方换行

// 换行符为\n,在需要换行的地方加上这个符号即可,如 
label.numberOfLines = 0;
label.text = @"此处\n换行";

80.摇一摇功能

1、打开摇一摇功能
 [UIApplication sharedApplication].applicationSupportsShakeToEdit = YES;
 2、让需要摇动的控制器成为第一响应者
 [self becomeFirstResponder];
 3、实现以下方法
  // 开始摇动
  - (void)motionBegan:(UIEventSubtype)motion withEvent:(UIEvent *)event
  // 取消摇动
  - (void)motionCancelled:(UIEventSubtype)motion withEvent:(UIEvent *)event
  // 摇动结束
  - (void)motionEnded:(UIEventSubtype)motion withEvent:(UIEvent *)event

81.获取view的坐标在整个window上的位置

// v上的(0, 0)点在toView上的位置
CGPoint point = [v convertPoint:CGPointMake(0, 0) toView:[UIApplication sharedApplication].windows.lastObject];
或者
CGPoint point = [v.superview convertPoint:v.frame.origin toView:[UIApplication sharedApplication].windows.lastObject];

82.提交App Store审核程序限制

您的应用程序的未压缩大小必须小于4GB。每个Mach-O可执行文件(例如app_name.app/app_name)不能超过这些限制:
对于MinimumOSVersion小于7.0的应用程序:TEXT二进制文件中所有部分的总数最多为80 MB 。
对于MinimumOSVersion7.x到8.x的应用程序:TEXT对于二进制文件中每个体系结构片段的每个片段,最大为60 MB 。
对于MinimumOSVersion9.0或更高版本的应用程序:__TEXT二进制文件中所有部分的总数最多为500 MB 。参阅:iTunes Connect开发者指南

83.修改UISegmentedControl的字体大小

[segment setTitleTextAttributes:@{NSFontAttributeName : [UIFont systemFontOfSize:15.0f]} forState:UIControlStateNormal];

84.在非ViewController的地方弹出UIAlertController对话框

//  最好抽成一个分类
UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"Title" message:@"message" preferredStyle:UIAlertControllerStyleAlert];
id rootViewController = [UIApplication sharedApplication].delegate.window.rootViewController;
If([rootViewController isKindOfClass:[UINavigationController class]])
{
   rootViewController = ((UINavigationController *)rootViewController).viewControllers.firstObject;
}
if([rootViewController isKindOfClass:[UITabBarController class]])
{
    rootViewController = ((UITabBarController *)rootViewController).selectedViewController;
}
 [rootViewController presentViewController:alertController animated:YES completion:nil];

85.获取一个view所属的控制器

// view分类方法
 - (UIViewController *)belongViewController {
for (UIView *next = [self superview]; next; next = next.superview) {
    UIResponder* nextResponder = [next nextResponder];
    if ([nextResponder isKindOfClass:[UIViewController class]]) {
        return (UIViewController *)nextResponder;
    }
}
   return nil;
}

86.UIImage和base64互转

// view分类方法
 - (NSString *)encodeToBase64String:(UIImage *)image {
 return [UIImagePNGRepresentation(image) base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength];
 }
- (UIImage *)decodeBase64ToImage:(NSString *)strEncodeData {
  NSData *data = [[NSData alloc]initWithBase64EncodedString:strEncodeData options:NSDataBase64DecodingIgnoreUnknownCharacters];
  return [UIImage imageWithData:data];
}

87.UIWebView设置背景透明

[webView setBackgroundColor:[UIColor clearColor]];
 [webView setOpaque:NO];

88.判断NSDate是不是今天

NSDateComponents *otherDay = [[NSCalendar currentCalendar] components:NSCalendarUnitEra | NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay fromDate:aDate];
NSDateComponents *today = [[NSCalendar currentCalendar] components:NSCalendarUnitEra | NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay fromDate:[NSDate date]];
if([today day] == [otherDay day] && [today month] == [otherDay month] &&[today year] == [otherDay year] && [today era] == [otherDay era]) {
    // 是今天
}

89.设置tableView分割线颜色

[self.tableView setSeparatorColor:[UIColor myColor]];

90.设置屏幕方向

[[UIDevice currentDevice] setValue:@(UIInterfaceOrientationLandscapeLeft) forKey:@"orientation"];

91.UITextView中打开或禁用复制,剪切,选择,全选等功能

// 继承UITextView重写这个方法
- (BOOL)canPerformAction:(SEL)action withSender:(id)sender
{
    // 返回NO为禁用,YES为开启
    // 粘贴
    if (action == @selector(paste:)) return NO;
    // 剪切
    if (action == @selector(cut:)) return NO;
    // 复制
    if (action == @selector(copy:)) return NO;
    // 选择
    if (action == @selector(select:)) return NO;
    // 选中全部
    if (action == @selector(selectAll:)) return NO;
    // 删
    if (action == @selector(delete:)) return NO;
    // 分享
    if (action == @selector(share)) return NO;
       return [super canPerformAction:action withSender:sender];
 }

92.屏幕截图

/**
   *    @brief  屏幕截图
   */
  + (UIImage *)screenShotWithView:(UIView *)v;
  + (UIImage *)screenShotWithView:(UIView *)v;
  {
     UIGraphicsBeginImageContext(v.frame.size);
     [v.layer renderInContext:UIGraphicsGetCurrentContext()];
     UIImage *img = UIGraphicsGetImageFromCurrentImageContext();
     UIGraphicsEndImageContext();
     return img;
   }

93.获取视频的第一帧图片

-(UIImage *)videoUrl:(NSString *)url{
     NSURL *urlString = [NSURL URLWithString:url];
     AVURLAsset *asset1 = [[AVURLAsset alloc] initWithURL:urlString options:nil];
     AVAssetImageGenerator *generate1 = [[AVAssetImageGenerator alloc] initWithAsset:asset1];
     generate1.appliesPreferredTrackTransform = YES;
     NSError *err = NULL;
     CMTime time = CMTimeMake(1, 2);
     CGImageRef oneRef = [generate1 copyCGImageAtTime:time actualTime:NULL error:&err];
     UIImage *oneImage = [[UIImage alloc] initWithCGImage:oneRef];
     return oneImage;
 }


目录
相关文章
|
5月前
|
XML JSON Java
Java开发常用代码总结和分享
Java开发常用代码总结和分享
27 0
|
6月前
奇淫技巧系列第三篇:阅读源码时基于一组快捷键让我们知道身在何方!
奇淫技巧系列第三篇:阅读源码时基于一组快捷键让我们知道身在何方!
|
IDE Java Go
代码搜索技巧
代码搜索技巧
67 0
|
API Windows
VBA 有用的小段代码收藏(日积月累)
VBA 有用的小段代码收藏(日积月累)
128 0
|
前端开发 JavaScript 开发工具
前端CSS常用代码集合
前端CSS常用代码集合
|
iOS开发 Windows
iOS开发:平时做项目经常用到的快捷键归纳
从事了这么久编程工作,总结了好多知识,但是本人之前从来没有写博客的习惯,通过去年的一次面试,明白了,不写技术博客会被面试官鄙视,所以本人痛下决心,要改变这个不爱写博客的现状,只要有时间,我就把我从开始iOS编程到现在,总结的所有内容都贴出来,之前是直接截图或者word文档,存在自己电脑里面,现在是时候把它们贴出来了。
143 0
iOS开发:平时做项目经常用到的快捷键归纳
|
Java Spring
编程小技巧7-配置文件自动提示功能消失解决方案
编程小技巧7-配置文件自动提示功能消失解决方案
141 0
编程小技巧7-配置文件自动提示功能消失解决方案
|
机器学习/深度学习 Python
小习惯随手记:Python编程时将常引用的基础工具包放在一个头文件中
小习惯随手记:Python编程时将常引用的基础工具包放在一个头文件中
小习惯随手记:Python编程时将常引用的基础工具包放在一个头文件中
|
数据库
代码写的垃圾被嫌弃?这 3 个插件你值得拥有…
今天推荐三个插件,它们都是代码质量检测的神器。可以扫描检测出你项目中不符合规范的代码,他们分别是 SonarLint、SonarQube、Alibaba代码规约插件。
228 0
代码写的垃圾被嫌弃?这 3 个插件你值得拥有…