JoanKing常用代碼

獲取window的三種方式(最后一種最靠譜)

UIWindow *window =   self.view.window ;
UIWindow *window =  [UIApplication sharedApplication].keyWindow;
UIWindow *window = [[UIApplication sharedApplication].windows lastObject];

簡述:宏定義的后面沒有符號

0.0.Block的使用

(1) 方法調用block

  1.在.h里面(建立吧bock)和設置block的方法
  typedef void(^BLOCK)(NSString *name);
  -(void)setBlock:(BLOCK)block;(在.m屬性需要實現)
  2.在.m里面進行實現block方法和屬性的轉換
  先利用BLOCK設置一個屬性 BLOCK valueBlock;
  -(void)setBlock:(BLOCK)block
  {
      valueBlock = block;
  }
  3.在點擊的調用的方法里面進行調用

  valueBlock(這里放一個字符串傳到外面);
  4.在外面調用

  [類的對象 setBlock:^(NSString *name) {

     這里進行執行block這個方法
 }];

(2) 屬性調用block

 1.在.h里面設置2個字符串
 @property(nonatomic,strong) void(^guwen)(NSString *paGe,NSString *name);
 2.在.m里面點擊調用
 if (self.guwen) {
      self.guwen(pageNumber,self.nameLabel.text);
  }
 3.在外面把值取出來
 利用這個類的對象進行調用

  累的對象.guwen = ^(NSString *paGe,NSString *name){

     在此進行調用傳值
  };

0.Profile文件的設置

 platform :ios,’7.0’
 target “JLCardAnimation” do
 pod 'AFNetworking', '~> 3.1.0'
 pod 'MJExtension', '~> 3.0.13'
 pod 'SDWebImage', '~> 3.8.1'
 end

1.尺寸的宏定義

 寬高的設置
 #define WIDTH   [UIScreen mainScreen].bounds.size.width
 #define HEIGHT  [UIScreen mainScreen].bounds.size.height
 尺寸的設置
 #define iPhone5AndEarlyDevice (([[UIScreen mainScreen] bounds].size.height*[[UIScreen mainScreen] bounds].size.width <= 320*568)?YES:NO)
 #define Iphone6 (([[UIScreen mainScreen] bounds].size.height*[[UIScreen mainScreen] bounds].size.width <= 375*667)?YES:NO)

2.顏色的宏定義

 //RGB顏色
 #define CWColor(r,g,b)  [UIColor colorWithRed:(r)/255.0 green:(g)/255.0 blue:(b)/255.0 alpha:1.0]
 //隨機色(和上面的保持 一致)
 #define CWRandomColor  CWColor(arc4random_uniform(256),arc4random_uniform(256),arc4random_uniform(256))
 自定義隨機色
 #define CWRandomColor  [UIColor colorWithRed:arc4random_uniform(256)/255.0 green:arc4random_uniform(256)/255.0  blue:arc4random_uniform(256)/255.0  alpha:1.0]

3.開發模式(名字自己起)

 #ifdef DEBUG     //處于開發階段才打印(調試)
 #define CWLog(...) NSLog(__VA_ARGS__)
 #else            //處于發布階段(沒有輸出)(發布)
 #define CWLog(...)
 #endif

4.NSUserDefaults取值,存值

//取值
#define UserDefaultObject(A) [[NSUserDefaults standardUserDefaults]objectForKey:A]
//存值(可變的值不可以存)
#define UserDefaultSetValue(B,C) [[NSUserDefaults standardUserDefaults]setObject:B forKey:C]
//存BOOL值
#define UserDefaultBool(D,E)  [[NSUserDefaults standardUserDefaults]setBool:D forKey:E]

5.弱引用

__weak typeof(self) weakSelf = self;
/*
     弱引用
 */
#define STWeakSelf __weak typeof(self) weakSelf = self;

6.判斷版本是ios7以后版本

#define IOS_CURRENT_VERSION_IOS7 ([[UIDevice currentDevice].systemVersion floatValue] < 7.0 ? NO : YES)

7.打印函數,可以打印所在的函數,行數,以及你要打印的值

#define DLog(fmt, ...) NSLog((@"%s [Line %d] " fmt), __PRETTY_FUNCTION__, __LINE__, ##__VA_ARGS__);
NSLog(@"==1==%s 2==[Line %d] 3==%@", __PRETTY_FUNCTION__, __LINE__,string);

8.cell高度根據文本來確定(注意字體的大小和外面的保持一致)

CGFloat height =[@"文字的內容" boundingRectWithSize:CGSizeMake([UIScreen mainScreen].bounds.size.width-20, CGFLOAT_MAX) options:NSStringDrawingUsesLineFragmentOrigin attributes:[NSDictionary dictionaryWithObject:[UIFont systemFontOfSize:11] forKey:NSFontAttributeName] context:nil].size.height;

9.請求,上拉,下拉刷新

一般都有頁碼和數組

NSArray *tempArray;
NSMutableArray *dataArray;
@property(nonatomic,assign) int p;

-(void)refreshData
{
self.tableView.mj_header= [MJRefreshNormalHeader headerWithRefreshingBlock:^{
    
    self.p = 1;
    dataArray = [[NSMutableArray alloc]init];
    [HUD showLoadingHUDWithText:@"加載中..." inView:self.view];
    //調用網絡請求的方法
    [self request:1];
    
}];
self.tableView.mj_footer = [MJRefreshAutoFooter footerWithRefreshingBlock:^{
    
    self.p ++;
    [HUD showLoadingHUDWithText:@"加載中..." inView:self.view];
     //調用網絡請求的方法
    [self request:self.p];
   }];
}

10.網絡請求

-(void)request:(int)pp
{
  self.title = @"酒店";
  #define DFTurl @"http://192.168.80.254"
  NSString *url = [NSString stringWithFormat:@"%@/jiekou/index.php?g=home&m=index&a=jiudian&p=%d",DFTurl,pp];
  dispatch_async(dispatch_get_global_queue(0, 0), ^{
    /*
        網絡數據的請求
     */
    [[SXHTTPEngine shareManager]POST:url params:nil success:^(id responseObject) {
        
        DFTLog(@"====%@",responseObject);
        tempArray = responseObject[@"data"];
        
        tempArray = [HostelHomeModel mj_objectArrayWithKeyValuesArray:tempArray];
        [dataArray addObjectsFromArray:tempArray];
        [HUD hideHUD];
        /*
           刷新主線程
         */
        dispatch_async(dispatch_get_main_queue(), ^{
            
            [self.tableView reloadData];
            /*
                上拉下拉刷新的截止
             */
            [self.tableView.mj_header endRefreshing];
            [self.tableView.mj_footer endRefreshing];
        });
        
    } failure:^(NSError *error) {
        
        DFTLog(@"加載失敗");
        /*
                上拉下拉刷新的截止
         */
        [self.tableView.mj_header endRefreshing];
        [self.tableView.mj_footer endRefreshing];
        [HUD showLoadingHUDWithText:@"加載失敗"];
        [HUD hideHUD];
    }];
  });
}

11. 設置導航欄文字的顏色以及文字大小(如導航的背景顏色,以及導航欄中間字體的顏色)

/*
設置導航欄文字的顏色以及文字大小(如導航的背景顏色,以及導航欄中間字體的顏色)
[UINavigationBar appearance];
設置Item的樣式
[UIBarButtonItem appearance];
*/
//在第一次使用調用一次
+(void)initialize
{
    //設置整個項目所有item的主題樣式()
    UIBarButtonItem *item = [UIBarButtonItem appearance];

    //設置普通狀態的字體顏色和大小
    [item setTitleTextAttributes:@{NSForegroundColorAttributeName:CWColor(123, 123, 123),NSFontAttributeName:[UIFont systemFontOfSize:20]} forState:UIControlStateNormal];

    //設置點擊的時候顏色和大小
    [item setTitleTextAttributes:@{NSForegroundColorAttributeName:CWColor(252, 108, 8),NSFontAttributeName:[UIFont systemFontOfSize:20]} forState:UIControlStateSelected];
}

導航欄上button圖片防止被渲染

UIImage *img = [[UIImage imageNamed:@"icon_cog"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
//寬度為負數的固定間距的系統item
UIBarButtonItem *rightNegativeSpacer = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace target:nil action:nil];
[rightNegativeSpacer setWidth:-15];

UIBarButtonItem *rightBtnItem1 = [[UIBarButtonItem alloc]initWithImage:img style:UIBarButtonItemStylePlain target:self action:@selector(rightButtonItemClicked:)];
UIBarButtonItem *rightBtnItem2 = [[UIBarButtonItem alloc]initWithImage:img style:UIBarButtonItemStylePlain target:self action:@selector(rightButtonItemClicked:)];
self.navigationItem.rightBarButtonItems = @[rightNegativeSpacer,rightBtnItem1,rightBtnItem2];

12 NSData 轉化我 string

/*
     1.把 NSData 轉化我 string
 */

NSString *string = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
/*
     2.把string 轉化我 NSData
 */
NSData *data = [respondString dataUsingEncoding:NSUTF8StringEncoding]


//NSString轉化為NSNumber
NSString *string = @"9000";
NSNumber *number = @([string integerValue]);
NSLog(@"number=%@",number);

//NSNumber轉化為NSString
NSString *string1 = [NSString stringWithFormat:@"%@",number];
NSLog(@"string1=%@",string1);

13主線程刷新

   <1>.GCD
   dispatch_async(dispatch_get_main_queue(), ^{
     
    });
 
   <2>.NSOperation
    [[NSOperationQueue mainQueue]addOperationWithBlock:^{
        
    }];

13.改變圖片的大小

 我們需要傳UIImage  和  CGSize   返回的還是UIImage

- (UIImage *)scaleToSize:(UIImage *)img size:(CGSize)newsize{
 // 創建一個bitmap的context
 // 并把它設置成為當前正在使用的context
 UIGraphicsBeginImageContext(newsize);
 // 繪制改變大小的圖片
 [img drawInRect:CGRectMake(0, 0, newsize.width, newsize.height)];
 // 從當前context中創建一個改變大小后的圖片
 UIImage* scaledImage = UIGraphicsGetImageFromCurrentImageContext();
 // 使當前的context出堆棧
 UIGraphicsEndImageContext();
 // 返回新的改變大小后的圖片
 return scaledImage;
}

14.有關block的使用

這僅僅是調用的展示

@property(strong,nonatomic)void(^agriculturalBtnClick)();
@property(strong,nonatomic)void(^forestryBtnClick)();
@property(strong,nonatomic)void(^AnimalBtnClick)();
-(void)homeBtnClick:(UIButton *)sender
{
   switch (sender.tag) {
    case 0:{
        if (self.agriculturalBtnClick) {
            self.agriculturalBtnClick();
        }
    }break;
    case 1:{
        if (self.forestryBtnClick) {
            self.forestryBtnClick();
        }
    }break;
    case 2:{
        if (self.AnimalBtnClick) {
            self.AnimalBtnClick();
        }
    }break;
  }
}
 /*
      下面是對方法的調用(這是cell里面的調用)
  */
  cell.agriculturalBtnClick = ^(){

   };
  cell.forestryBtnClick = ^(){

   };
  cell.AnimalBtnClick = ^(){

   };

15.一個方法的延遲執行(2s之后執行)

[self performSelector:@selector(logInShouYe) withObject:nil afterDelay:2];

16.打電話

  NSMutableString * str=[[NSMutableString alloc] initWithFormat:@"tel:%@",[user objectForKey:@"電話"]];
            UIWebView * callWebview = [[UIWebView alloc] init];
            [callWebview loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:str]]];
            [self.view addSubview:callWebview];

17.弱引用的使用

 __weak typeof(self) Wself = self;

18.UIWebView加載連接

NSURL *url = [NSURL URLWithString:@"http://www.pgyer.com/iHLM"];

NSURLRequest *request = [NSURLRequest requestWithURL:url];

UIWebView *webView = [[UIWebView alloc]initWithFrame:[UIScreen mainScreen].bounds];

[self.view addSubview:webView];

[webView loadRequest:request];

19.按鈕的點擊方法(其實只是縮放率的改變,動畫的加載)

按鈕的點擊放大,其實改變的只是按鈕的transform(縮放率)

  • 下面以一個button為例
UIButton  = [UIButton buttonWithType:UIButtonTypeCustom];
self.liekBtn.frame = CGRectMake(CGRectGetMaxX(self.disLikeBtn.frame)+100 , HEIGHT*0.5, 60, 60);
[self.liekBtn setImage:[UIImage imageNamed:@"likeBtn"] forState:UIControlStateNormal];
[self.liekBtn addTarget:self action:@selector(liek) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:self.liekBtn];

-(void)liek {

[UIView animateWithDuration:0.5
                 animations:^{
                     self.liekBtn.transform = CGAffineTransformMakeScale(1.2, 1.2);
                    
                 } completion:^(BOOL finished) {
                     
                     self.liekBtn.transform = CGAffineTransformMakeScale(1, 1);
                  
                 }];
}

3D放大

 對象.transform3D = CATransform3DMakeScale(x, y, z);

按鈕的點擊放大

20.手勢沖突的解決方式

//重寫手勢的方法 手勢會影響 cell的點擊
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch
{

if ([NSStringFromClass([touch.view class]) isEqualToString:@"UITableViewCellContentView"])
{
        return NO;
   }else{
        return YES;
   }
}

21打電話

掛代理 <UIActionSheetDelegate>

UIAlertView * alertView2 = [[UIAlertView alloc]initWithTitle:@"全國統一客服熱線:4007-114-115" message:nil delegate:self cancelButtonTitle:@"撥打" otherButtonTitles:@"取消", nil];

[alertView2 show];


- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
    UIWebView*callWebview =[[UIWebView alloc] init] ;
    NSURL *telURL =[NSURL URLWithString:[NSString stringWithFormat:@"tel://4007114115"]];
    [callWebview loadRequest:[NSURLRequest requestWithURL:telURL]];
    [self.backScrollView addSubview:callWebview];

    return;
}

22.導航欄的顏色

可以設置全局,也可以單獨設置
self.navigationController.navigationBar.titleTextAttributes = @{NSForegroundColorAttributeName : [UIColor whiteColor],NSFontAttributeName : [UIFont systemFontOfSize:20]};
/顏色自己隨便設置
self.navigationController.navigationBar.barTintColor = [UIColor colorWithRed:0.101 green:0.705 blue:0.652 alpha:1.000];

23.自定義導航控制器上面的按鈕

UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
//設置圖片的兩種狀態
//正常
[button setImage:[UIImage imageNamed:@"返回"] forState:UIControlStateNormal];
//選中
[button setImage:[UIImage imageNamed:@"返回"] forState:UIControlStateHighlighted];
button.frame = CGRectMake(0, 0, 30, 30);
[button addTarget:self action:@selector(back1) forControlEvents:UIControlEventTouchUpInside];
self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]initWithCustomView:button];

24.獲取版本號

//獲取版本號
NSString *version1 = [NSBundle mainBundle].infoDictionary[@"CFBundleShortVersionString"];

25.相機問題

最近做頭像上傳功能需要使用系統相冊、相機,在調用系統相冊、相機發現是英文的系統相簿界面后標題顯示“photos”,但是手機語言已經設置顯示中文,糾結半天,最終在info.plist設置解決問題。發現在項目的info.plist里面添加Localized resources can be mixed YES(表示是否允許應用程序獲取框架庫內語言)即可解決這個問題。特此記錄下以便以后查看和別人解決問題。

26.兩種跳轉展示

  • 1.中間展示(兩種寫法)
中間展示
 //第一種方法
  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.下面展示
下面展示
//第一種方法
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的方法,所以在此定義為宏使用更加方便簡潔!如下圖


//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.交換兩個值(異或)

交換值

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;
 }
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市,隨后出現的幾起案子,更是在濱河造成了極大的恐慌,老刑警劉巖,帶你破解...
    沈念sama閱讀 230,002評論 6 542
  • 序言:濱河連續發生了三起死亡事件,死亡現場離奇詭異,居然都是意外死亡,警方通過查閱死者的電腦和手機,發現死者居然都...
    沈念sama閱讀 99,400評論 3 429
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人,你說我怎么就攤上這事。” “怎么了?”我有些...
    開封第一講書人閱讀 178,136評論 0 383
  • 文/不壞的土叔 我叫張陵,是天一觀的道長。 經常有香客問我,道長,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 63,714評論 1 317
  • 正文 為了忘掉前任,我火速辦了婚禮,結果婚禮上,老公的妹妹穿的比我還像新娘。我一直安慰自己,他們只是感情好,可當我...
    茶點故事閱讀 72,452評論 6 412
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著,像睡著了一般。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發上,一...
    開封第一講書人閱讀 55,818評論 1 328
  • 那天,我揣著相機與錄音,去河邊找鬼。 笑死,一個胖子當著我的面吹牛,可吹牛的內容都是我干的。 我是一名探鬼主播,決...
    沈念sama閱讀 43,812評論 3 446
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了?” 一聲冷哼從身側響起,我...
    開封第一講書人閱讀 42,997評論 0 290
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后,有當地人在樹林里發現了一具尸體,經...
    沈念sama閱讀 49,552評論 1 335
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內容為張勛視角 年9月15日...
    茶點故事閱讀 41,292評論 3 358
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發現自己被綠了。 大學時的朋友給我發了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 43,510評論 1 374
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖,靈堂內的尸體忽然破棺而出,到底是詐尸還是另有隱情,我是刑警寧澤,帶...
    沈念sama閱讀 39,035評論 5 363
  • 正文 年R本政府宣布,位于F島的核電站,受9級特大地震影響,放射性物質發生泄漏。R本人自食惡果不足惜,卻給世界環境...
    茶點故事閱讀 44,721評論 3 348
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧,春花似錦、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 35,121評論 0 28
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至,卻和暖如春,著一層夾襖步出監牢的瞬間,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 36,429評論 1 294
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人。 一個月前我還...
    沈念sama閱讀 52,235評論 3 398
  • 正文 我出身青樓,卻偏偏與公主長得像,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當晚...
    茶點故事閱讀 48,480評論 2 379

推薦閱讀更多精彩內容