iOS--小知識點

iOS--小知識點

一. 顏色漸變

CAGradientLayer *gradientLayer = [CAGradientLayer layer];
gradientLayer.colors = @[(__bridge id)[UIColor whiteColor].CGColor, (__bridge id)[UIColor grayColor].CGColor, (__bridge id)[UIColor whiteColor].CGColor];
gradientLayer.locations = @[@0.0, @0.5, @1.0];
gradientLayer.startPoint = CGPointMake(0, 0);
gradientLayer.endPoint = CGPointMake(1.0, 0);
gradientLayer.frame = CGRectMake(0, 100, 300, 2);
[self.view.layer addSublayer:gradientLayer];

三. 使用drowRect繪制簡單圖形

//獲取上下文    CGContextRef 
context=UIGraphicsGetCurrentContext();    //設置繪制地區的顏色  
CGContextSetRGBFillColor(context, 1, 0, 0, 1);    //設置繪制的位置和大小    
CGContextFillRect(context, CGRectMake(0, 100, 100, 100)); 
NSString * text=@"文字";    
UIFont * font=[UIFont systemFontOfSize:14];
[text drawAtPoint:CGPointMake(0, 200) withAttributes:font.fontDescriptor.fontAttributes];    
UIImage *img=[UIImage imageNamed:@""];    
[img drawInRect:CGRectMake(0, 300, 100, 100)];

四. 可變數組與不可變數組之間的轉換

NSMutableArray * mutablearray=[[NSMutableArray alloc]initWithCapacity:0];   
NSArray *copyarray=[mutablearray copy];    
copyarray=@[@"1",@"2",@"3"];    
NSArray *array = [[NSArray alloc]init];    
NSMutableArray *copymutablearray=[array mutableCopy];    
[copymutablearraysetObject:@"加入到第一位"atIndexedSubscript:0];    
[copymutablearray addObject:@"排序加入"];    
[copymutablearray addObjectsFromArray:copyarray];

五. 快速求和,最大值,最小值,平均值

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];

六. 對控件的旋轉,平移,縮放,復位

//平移
CGAffineTransform transForm = _pingyibu.transform;
_pingyibu.transform=CGAffineTransformTranslate(transForm, 100, 0);

//旋轉
_pingyibu.transform = CGAffineTransformRotate(transForm, M_PI_4);

//縮放按鈕
_pingyibu.transform = CGAffineTransformScale(transForm, 1.2, 1.2);

//初始化復位
_pingyibu.transform = CGAffineTransformIdentity;

七. 設置label的行間距

NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:_xuanzhuanla.text];    
NSMutableParagraphStyle *paragraphStyle =  [[NSMutableParagraphStyle alloc] init];  
[paragraphStylesetLineSpacing:3];    //調整行間距  
[attributedString addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:NSMakeRange(0,[_xuanzhuanla.text length])];    
_xuanzhuanla.attributedText = attributedString;

八. 讓應用直接閃退

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

九. 手機震動

AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);

十一. label自適應高度

CGRect rect = [la.text boundingRectWithSize:CGSizeMake(WIDTH-70, MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin|NSStringDrawingUsesFontLeading attributes:@{NSFontAttributeName:la.font} context:nil];

十三. image轉換成data類型

NSData *data=UIImagePNGRepresentation(image);
NSData *data=UIImageJPEGRepresentation(image, 1.0);

十四. 獲取當前時間和時間戳

//當前時間NSDate *senddate=[NSDate date];        
NSDateFormatter  *dateformatter=[[NSDateFormatter alloc] init]; 
[dateformattersetDateFormat:@"YYYY-MM-dd HH:mm:ss"];
NSString *locationString=[dateformatter stringFromDate:senddate];

//當前時間戳
NSDate* dat = [NSDate dateWithTimeIntervalSinceNow:0];        
NSTimeInterval a=[dat timeIntervalSince1970];        
NSString *timeString = [NSString stringWithFormat:@"%f", a];       
long s = [timeString intValue];

十五. 對比時間差

-(int)max:(NSDate *)datatime {    
//創建日期格式化對象    
NSDateFormatter *dateFormatter=[[NSDateFormatter alloc] init]; 
[dateFormattersetDateFormat:@"YYYY-MM-dd hh:mm:ss"];  
NSDate *senddate=[NSDate date];    
NSString *locationString=[dateFormatter stringFromDate:senddate];    
NSDate *date=[dateFormatter dateFromString:locationString];    
//取兩個日期對象的時間間隔:    
//這里的NSTimeInterval 并不是對象,是基本型,其實是double類型,是由c定義的:typedef double NSTimeInterval;   
NSTimeInterval time=[date timeIntervalSinceDate:datatime];    
int days=((int)time)/(3600*24);
return days;
}

十六. 使提示框消失(定時)

[alu dismissWithClickedButtonIndex:0 animated:NO];

十七. 設置self.title的顏色

UIColor *color = [UIColor whiteColor];
NSDictionary * dict=[NSDictionary dictionaryWithObject:colorforKey:UITextAttributeTextColor];
self.navigationController.navigationBar.titleTextAttributes = dict;

十八. 請求定位權限以及定位屬性

//定位管理器    
_locationManager = [[CLLocationManager alloc]init];    
//如果沒有授權則請求用戶授權
if([CLLocationManager authorizationStatus]==kCLAuthorizationStatusNotDetermined){ 
[_locationManager requestWhenInUseAuthorization];    
} else if([CLLocationManager authorizationStatus]==kCLAuthorizationStatusAuthorizedWhenInUse){       
 //設置代理        
_locationManager.delegate=self;        
//設置定位精度       
 _locationManager.desiredAccuracy = kCLLocationAccuracyBest; 
//定位頻率,每隔多少米定位一次        
CLLocationDistance distance=10.0;
_locationManager.distanceFilter = distance;       
//啟動跟蹤定位      
[_locationManager startUpdatingLocation];   
 }

十九. 通過經緯度計算距離

BOOL JuLi = NO;    
CLLocation *orig = [[CLLocation alloc] initWithLatitude:oldlat  longitude:oldlong];    
CLLocation* dist = [[CLLocation alloc] initWithLatitude:nowlat longitude:nowlong];    
CLLocationDistance kilometers = [orig distanceFromLocation:dist];    
NSLog(@"距離:%f",kilometers);
if(kilometers >= 10) {
     JuLi=YES;    
}else{        
     JuLi=NO;    
}
return JuLi;

二十. 彈出效果

/** 彈出對話框的動畫  動畫時長
@param changeOutView
@param dur          
/*
-(void)exChangeOut:(UIView *)changeOutView dur:(CFTimeInterval)dur{    
CAKeyframeAnimation *animation;    
animation = [CAKeyframeAnimation animationWithKeyPath:@"transform"];    
animation.duration = dur;    
animation.delegate = self;    
animation.removedOnCompletion = NO;    
animation.fillMode = kCAFillModeForwards;    
NSMutableArray *values = [NSMutableArray array];    
[values addObject:[NSValue valueWithCATransform3D:CATransform3DMakeScale(0.1, 0.1, 1.0)]];    
[values addObject:[NSValue valueWithCATransform3D:CATransform3DMakeScale(1.2, 1.2, 1.0)]];    
[values addObject:[NSValue valueWithCATransform3D:CATransform3DMakeScale(0.9, 0.9, 0.9)]];    
[values addObject:[NSValue valueWithCATransform3D:CATransform3DMakeScale(1.0, 1.0, 1.0)]];    
animation.values = values;    
animation.timingFunction = [CAMediaTimingFunctionfunctionWithName: @"easeInEaseOut"];   [changeOutView.layer addAnimation:animationforKey:nil];
}

二十一. 設置TextField左右視圖

-(id)initWithFrame:(CGRect)frame drawingLeft:(UIImageView *)icon drawingRight:(UIButton *)bu{
self = [super initWithFrame:frame];
if(self) {        
   self.leftView = icon;        
   self.leftViewMode = UITextFieldViewModeAlways;           
   self.rightView= bu;        
   self.rightViewMode=UITextFieldViewModeAlways;    
}
   return self;
}
-(CGRect)leftViewRectForBounds:(CGRect)bounds{    
   CGRect iconRect = [super leftViewRectForBounds:bounds];        
   iconRect.origin.x += 5;
   return iconRect;
}
-(CGRect)rightViewRectForBounds:(CGRect)bounds{    
   CGRect burect = [super rightViewRectForBounds:bounds];    
   burect.origin.x +=-10;
   return burect;
}

二十二. 常用宏定義

#define PUSH(x) AppDelegate *appdelegate=(AppDelegate *)[UIApplication sharedApplication].delegate;[(UINavigationController*)appdelegate.window.rootViewController pushViewController:x animated:YES];
#define POP AppDelegate *appdelegate=(AppDelegate *)[UIApplication sharedApplication].delegate;[(UINavigationController*)appdelegate.window.rootViewController popViewControllerAnimated:YES];
#define POPROOT OGPAppDelegate *appdelegate=(OGPAppDelegate *)[UIApplication sharedApplication].delegate;[(UINavigationController*)appdelegate.window.rootViewController popToRootViewControllerAnimated:YES];
#define IOS7 ([[UIDevice currentDevice].systemVersion floatValue] >= 7.0f)#define IPHONE_4INCH ([UIScreen mainScreen].bounds.size.height > 480.0f)
#define RANDOM_COLOR [UIColor colorWithRed:arc4random_uniform(256) / 255.0 green:arc4random_uniform(256) / 255.0 blue:arc4random_uniform(256) / 255.0 alpha:1]

二十三. 獲取版本號提示版本更新

-(void)VersionButton{    
NSString * string=[NSString stringWithContentsOfURL:[NSURL URLWithString:@"http://itunes.apple.com/lookup?id=??????????"] encoding:NSUTF8StringEncoding error:nil];
   if(string!=nil && [string length] > 0 && [string rangeOfString:@"version"].length==7) {        
   [self checkenAppUpdate:string];    
  }
}
-(void)checkenAppUpdate:(NSString *)appinfo{    
   NSString *version=[[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleVersion"];    
   NSString *appInfo1=[appinfo substringFromIndex:[appinfo rangeOfString:@"\"version\":"].location+10];   
   appInfo1 = [[appInfo1 substringToIndex:[appInfo1 rangeOfString:@","].location] stringByReplacingOccurrencesOfString:@"\""withString:@""];
   if(![appInfo1 isEqualToString:version]) {        
      UIAlertView * alert=[[UIAlertView alloc]initWithTitle:@"" message [NSString stringWithFormat:@"新版本%@, 已經發布",appInfo1] delegate:self cancelButtonTitle:@"知道了"otherButtonTitles: nil];   
      alert.delegate=self;        
      [alert addButtonWithTitle:@"前往更新"];       
      [alert show];        
      alert.tag=20;    
   }
}
-(void)alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex {
   if(buttonIndex==1 & alertView.tag==20) {        
       NSString *url=@"https://appsto.re/cn/-naScb.i";       
      [[UIApplication sharedApplication] openURL:[NSURL URLWithString:url]];    
   }
}

二十四. 獲取設備或APP信息

//返回應用程序名稱
+(NSString *) getAppName{    NSDictionary *infoDictionary = [[NSBundle mainBundle] infoDictionary];
   return[infoDictionary objectForKey:@"CFBundleDisplayName"];
}
//返回應用版本號+(NSString *) getAppVersion{    NSDictionary *infoDictionary = [[NSBundle mainBundle] infoDictionary];
   return[infoDictionary objectForKey:@"CFBundleShortVersionString"];
}
+(NSString *) getAppBundleVersion{    
   NSDictionary *infoDictionary = [[NSBundle mainBundle] infoDictionary];
   return [infoDictionary objectForKey:@"CFBundleVersion"];
}
//設備型號
+(NSString *) getSystemName{
   return [[UIDevice currentDevice] systemName];
}
//設備版本號
+(NSString *) getSystemVersion{
   return[[UIDevice currentDevice] systemVersion];
}

二十五. 內存泄漏分析

靜態分析內存泄露 使用Xcode自帶的Analyze功能
(Product-> Analyze)(Shift + Command + B),對代碼進行靜態分析,
對于內存泄露(Potential Memory Leak), 未使用局部變量(dead store),
邏輯錯誤(Logic Flaws)以及API使用問題(API-usage)等明確的展示出來。 
靜態分析的內存泄露情況比較簡單,開發者都能很快的解決。這里不做贅述。

動態分析內存泄露 使用Xcode自帶的Profile功能
(Product-> Profile)(Command + i)彈出工具框,
選擇Leaks打開,選擇運行設備點左上角的Record錄制按鈕,
項目就會在已選好的設備上運行,并開始錄制內存檢測情況。
選Leaks查看泄露情況,在Leaks的詳細菜單Details選項里選調用樹Call Tree,
可查看所有內存泄露發生在哪些地方。
再在右側的齒輪設置-Call Tree-勾選Hide System Libraries,
則可直接看內存泄露發生的函數名、方法名。
點擊函數名、方法名,可直接跳到函數方法的細節,
可以看到哪一句代碼出現了內存泄露,以及泄露了多少內存。

接下來就要回到Xcode,找到出現內存泄露的函數方法,仔細分析如何出現的內存泄露;
 一般使用ARC,按照上面一提到的內存理解和編碼習慣是不會出現內存泄露的。
但我們在開發過程中,經常要使用第三方的一些類庫,特別是涉及到加密的類庫,
用c或c++來編碼的加密解密方法,會出現內存泄露。
此時,我們要明白這些內存分配,需要手動釋放。
要一步一步看,哪里分配了內存,在使用完之后一定要記得釋放free它。

二十六. block循環利用導致內存泄漏

A *a = [[A alloc] init]; 
a.finishBlock = ^(NSDictionary paraments){
    [adoSomething]; 
}; 
//對于這種在block塊里引用對象a的情況,要在創建對象a時加修飾符block來防止循環引用。 
block A *a = [[A alloc] init]; 
a.finishBlock = ^(NSDictionary paraments){
   [a doSomething]; 
}; 
//或 
A __block a = [[A alloc] init]; 
a.finishBlock = ^(NSDictionary paraments){ 
   [a doSomething]; 
}; 
//或者,需要在block中調用用self的方法、屬性、變量時,可以這樣寫
__weak typeof(self) weakSelf = self;
//在block中使用weakSelf。 
__weak typeof(self) weakSelf = self;
[bdoSomethingWithFinishBlock:^{ 
   weakSelf.text = @"內存檢測"; 
   [weakSelfdoSomething]; 
}];

二十七. label 的空格屬性和局部字段顏色

//設置 label 的 autoresizingMask 為 NO ,可以使用空格間隔字符串!  
NSMutableAttributedString *hintString=[[NSMutableAttributedString alloc]initWithString:@"點擊注冊按鈕服務協議"];      
//獲取要調整顏色的文字位置,調整顏色      
NSRange range1=[[hintString string]rangeOfString:@"注冊"];     
[hintString addAttribute:NSForegroundColorAttributeName value:[UIColor greenColor] range:range1];      
NSRange range2=[[hintString string]rangeOfString:@"服務協議"]; 
[hintString addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:range2];     
hintLabel.attributedText=hintString;

二十八. 過濾特殊字符

// 定義一個特殊字符的集合    
NSCharacterSet *set= [NSCharacterSet characterSetWithCharactersInString:    @"@/:;()¥「」"、[]{}#%-*+=_\\|~<>$€^?'@#$%^&*()_+'\""];    
// 過濾字符串的特殊字符    
NSString *newString = [trimString stringByTrimmingCharactersInSet:set];

二十九. 設置滑動的時候隱藏 navigationbar

//第1種: 
navigationController.hidesBarsOnSwipe = Yes    
//第2種: 當我們的手離開屏幕時候隱藏    
- (void)scrollViewWillEndDragging:(UIScrollView *)scrollView withVelocity:(CGPoint)velocity targetContentOffset:(inout CGPoint *)targetContentOffset { 
 if(velocity.y > 0){    
   [self.navigationControllersetNavigationBarHidden:YES animated:YES];        
} else {        
   [self.navigationControllersetNavigationBarHidden:NO animated:YES];        
}    
}    
//velocity.y這個量,在上滑和下滑時,變化極?。ㄐ担且驗榉较虿煌?,有正負之分,這就很好處理了。

三十. 屏幕截圖

// 1. 開啟一個與圖片相關的圖形上下文
UIGraphicsBeginImageContextWithOptions(self.view.bounds.size,NO,0.0);
// 2. 獲取當前圖形上下文
CGContextRef ctx = UIGraphicsGetCurrentContext();=
// 3. 獲取需要截取的view的layer
[self.view.layer renderInContext:ctx];
// 4. 從當前上下文中獲取圖片
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
// 5. 關閉圖形上下文
UIGraphicsEndImageContext();
// 6. 把圖片保存到相冊
UIImageWriteToSavedPhotosAlbum(image, nil, nil, nil);

三十一. 去掉 tabbar 和 navgationbar 的黑線

//去掉tabBar頂部線條    
CGRect rect = CGRectMake(0, 0, 1, 1);    UIGraphicsBeginImageContext(rect.size);    
CGContextRef context = UIGraphicsGetCurrentContext();  
CGContextSetFillColorWithColor(context, [[UIColor clearColor] CGColor]);    
CGContextFillRect(context, rect);    
UIImage *img = UIGraphicsGetImageFromCurrentImageContext();  
UIGraphicsEndImageContext();  
[self.tabBarsetBackgroundImage:img];  
[self.tabBarsetShadowImage:img];  
//[self.navigationController.navigationBarsetBackgroundImage:img];    
//self.navigationController.navigationBar.shadowImage = ima;  
self.tabBar.backgroundColor = SLIVERYCOLOR;

三十二. 判斷字符串中是否含有中文

-(BOOL)isChinese:(NSString *)str{        
   NSString *match=@"(^[\u4e00-\u9fa5]+$)";        
   NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF matches %@", match];
   return [predicate evaluateWithObject:str];   
}

三十三. 解決父視圖和子視圖的手勢沖突問題

/** 解決手勢沖突 */    
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch { 
   if([touch.view isDescendantOfView:cicView]) {
      returnNO;     
   } 
     returnYES;   
}

三十四. 獲取當前連接的Wi-Fi的名稱

NSString *wifiName = @"Not Found";        
CFArrayRef myArray = CNCopySupportedInterfaces();
   if(myArray != nil) {
      CFDictionaryRef myDict = CNCopyCurrentNetworkInfo(CFArrayGetValueAtIndex(myArray, 0));
   if(myDict != nil) {
      NSDictionary *dict = (NSDictionary*)CFBridgingRelease(myDict);                
      wifiName = [dict valueForKey:@"SSID"];            
   }        
}

三十五. 跨控制器跳轉返回

for(UIViewController *controllerinself.navigationController.viewControllers) {
   if([controller isKindOfClass:[@“你要返回的控制器類名” class]])
   {
      [self.navigationController popToViewController:controller animated:YES];        
   }    
}

三十六. layer.cornerRadius 圓角流暢性的優化

loginBtn.layer.rasterizationScale = [UIScreen mainScreen].scale;

三十七. 導航欄和下方視圖間隔距離消失

self.automaticallyAdjustsScrollViewInsets=YES;

三十八. 毛玻璃效果(ios8.0以后的版本)

UIVisualEffectView *visualEffectView = [[UIVisualEffectView alloc] initWithEffect:[UIBlurEffect effectWithStyle:UIBlurEffectStyleLight]];
visualEffectView.frame = CGRectMake(0, 0, 320*[FlexibleFrame ratio], 180*[FlexibleFrame ratio]);
visualEffectView.alpha = 1.0;

三十九. 移動工程不需要配置路徑

創建.pch文件時 , BuildSetting 中的 Prefix Header 中的路徑開頭可以寫 $(SRCROOT)/工程地址, 
這樣寫的好處可以使你的挪動代碼不用手動更換路徑!

四十. 判斷兩個數組是否相同

NSArray *array1 = [NSArray arrayWithObjects:@"a", @"b", @"c",  nil];    
NSArray *array2 = [NSArray arrayWithObjects:@"d", @"a", @"c",  nil];    
bool bol =false;    
//創建倆新的數組    
NSMutableArray *oldArr = [NSMutableArray arrayWithArray:array1];    
NSMutableArray *newArr = [NSMutableArray arrayWithArray:array2];    
//對數組1排序
[oldArr sortUsingComparator:^NSComparisonResult(id obj1, id obj2) {
   return obj1 > obj2;    
 }];    
//對數組2排序
[newArr sortUsingComparator:^NSComparisonResult(id obj1, id obj2) { 
return obj1 > obj2;    
}];
if(newArr.count == oldArr.count) {        
   bol =true;
   for(int16_t i = 0; i < oldArr.count; i++) {            
      id c1 = [oldArr objectAtIndex:i];            
      id newc = [newArr objectAtIndex:i];
      if(![newc isEqualToString:c1]) {                
            bol =false;break;            
      }        
   }    
}
if(bol) {        
    NSLog(@" ------------- 兩個數組的內容相同!");    
}else{        
    NSLog(@"-=-------------兩個數組的內容不相同!");    
}

四十一. block

對于block,都應該使用copy來聲明,
原因是block來捕獲上下文的信息
[官方文檔]
https://link.juejin.im/?target=https%3A%2F%2Fdeveloper.apple.com%2Flibrary%2Fios%2Fdocumentation%2FCocoa%2FConceptual%2FProgrammingWithObjectiveC%2FWorkingwithBlocks%2FWorkingwithBlocks.html%23%2F%2Fapple_ref%2Fdoc%2Fuid%2FTP40011210-CH8-SW12

四十三. 計算一段NSString在視圖中渲染出來的尺寸

+ (CGSize)sizeOfString:(NSString *)textString font:(UIFont *)font bound:(CGSize)bound {      
   NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];     
   paragraphStyle.lineBreakMode = NSLineBreakByWordWrapping;      
   paragraphStyle.alignment = NSTextAlignmentLeft;
   if(font == nil) {          
      font = [UIFont systemFontOfSize:[UIFont systemFontSize]];         }      
   NSDictionary * attributes = @{NSFontAttributeName : font, NSParagraphStyleAttributeName : paragraphStyle}; 
   NSAttributedString* attributedString = [[NSAttributedString alloc] initWithString:textString attributes:attributes];
   return [TTTAttributedLabel sizeThatFitsAttributedString:attributedString                                              withConstraints:CGSizeMake(bound.width, 999)                                      limitedToNumberOfLines:0];  
}

四十四. 獲取相應的字體類型名

for(NSString *fontfamilynamein[UIFont familyNames])  { 
   NSLog(@"Family:'%@'",fontfamilyname);
   for(NSString *fontName in [UIFont fontNamesForFamilyName:fontfamilyname]) {
      NSLog(@"\tfont:'%@'",fontName);      
   }      
   NSLog(@"~~~~~~~~");  
}

四十五. Masonry和SVProgreaaHUD需要注意

使用Masonry約束TTTAttributedLabel的時候,
初始化TTTAttributedLabel需要設置frame為CGRectZero,
否則約束會不生效。

SVProgressHUD如果要自定義一些屬性,
比如loading狀態轉圈的顏色,
必須先設置style為SVProgressHUDStyleCustom,
這樣自定義的狀態才會生效。

四十六. 打印View所有子視圖

po [[self view]recursiveDescription]

四十七. layoutSubviews調用的調用時機

* 當視圖第一次顯示的時候會被調用
* 當這個視圖顯示到屏幕上了,點擊按鈕
* 添加子視圖也會調用這個方法
* 當本視圖的大小發生改變的時候是會調用的
* 當子視圖的frame發生改變的時候是會調用的
* 當刪除子視圖的時候是會調用的

四十八. UIImageView填充模式

@"UIViewContentModeScaleToFill",      // 拉伸自適應填滿整個視圖  
@"UIViewContentModeScaleAspectFit",  // 自適應比例大小顯示  
@"UIViewContentModeScaleAspectFill",  // 原始大小顯示  
@"UIViewContentModeRedraw",          // 尺寸改變時重繪  
@"UIViewContentModeCenter",          // 中間  
@"UIViewContentModeTop",              // 頂部  
@"UIViewContentModeBottom",          // 底部  
@"UIViewContentModeLeft",            // 中間貼左  
@"UIViewContentModeRight",            // 中間貼右  
@"UIViewContentModeTopLeft",          // 貼左上  
@"UIViewContentModeTopRight",        // 貼右上  
@"UIViewContentModeBottomLeft",      // 貼左下  
@"UIViewContentModeBottomRight",      // 貼右下

四十九. MRC和ARC混編設置方式

在XCode中targets的build phases選項下Compile Sources下選擇 不需要arc編譯的文件 
雙擊輸入 -fno-objc-arc 即可 
MRC工程中也可以使用ARC的類,
方法如下: 
在XCode中targets的build phases選項下Compile Sources下選擇要使用arc編譯的文件 
雙擊輸入 -fobjc-arc 即可

五十. 解決tableview的分割線短一截

-(void)viewDidLayoutSubviews { 
   if([self.tableView respondsToSelector:@selector(setSeparatorInset:)]) {
      [self.tableViewsetSeparatorInset:UIEdgeInsetsMake(0,0,0,0)];
} if ([self.tableView respondsToSelector:@selector(setLayoutMargins:)]) {
      [self.tableViewsetLayoutMargins:UIEdgeInsetsMake(0,0,0,0)]; 
   }
}
-(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cellforRowAtIndexPath:(NSIndexPath *)indexPath { 
   if([cell respondsToSelector:@selector(setSeparatorInset:)]) { 
      [cellsetSeparatorInset:UIEdgeInsetsZero]; 
   } if ([cell respondsToSelector:@selector(setLayoutMargins:)]){
      [cellsetLayoutMargins:UIEdgeInsetsZero]; 
   }
}

五十一. 修改textFieldplaceholder字體顏色和大小

textField.placeholder = @"username is in here!";  
[textFieldsetValue:[UIColor redColor]forKeyPath:@"_placeholderLabel.textColor"];  
[textFieldsetValue:[UIFont boldSystemFontOfSize:16]forKeyPath:@"_placeholderLabel.font"];

五十二. 修改狀態欄字體顏色

//只能設置兩種顏色,黑色和白色,系統默認黑色
//設置為白色方法:
(1)在plist里面添加Status bar style,值為UIStatusBarStyleLightContent(白色)或UIStatusBarStyleDefault(黑 色)
(2)在Info.plist中設置UIViewControllerBasedStatusBarAppearance 為NO

五十三.調用相機后狀態欄消失

[[UIApplication sharedApplication]setStatusBarHidden:NO animated:NO];
[[UIApplication sharedApplication]setStatusBarStyle:UIStatusBarStyleBlackTranslucent animated:YES];

五十四. 修改UIAlertController字體顏色

//修改title  
NSMutableAttributedString *alertControllerStr = [[NSMutableAttributedString alloc] initWithString:@"提示"];  
[alertControllerStr addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:NSMakeRange(0, 2)];  
[alertControllerStr addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:17] range:NSMakeRange(0, 2)];
if(alertController valueForKey:@"attributedTitle") {        
       [alertControllersetValue:alertControllerStrforKey:@"attributedTitle"];  
}  
//修改message  
NSMutableAttributedString *alertControllerMessageStr = [[NSMutableAttributedString alloc] initWithString:@"提示內容"];  
[alertControllerMessageStr addAttribute:NSForegroundColorAttributeName value:[UIColor greenColor] range:NSMakeRange(0, 4)];  
[alertControllerMessageStr addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:20] range:NSMakeRange(0, 4)];
if(alertController valueForKey:@"attributedMessage") {
    [alertControllersetValue:alertControllerMessageStrforKey:@"attributedMessage"];  
}
//修改按鈕字體顏色
UIAlertAction *defaultAction = [UIAlertAction actionWithTitle:@"Default"style:UIAlertActionStyleDefault handler:nil];
[alertController addAction:defaultAction];
if(cancelAction valueForKey:@"titleTextColor") {
      [cancelActionsetValue:[UIColor redColor]forKey:@"titleTextColor"];  
}

五十五. 使用鑰匙串保存設備唯一ID

//下載并倒入SSKeyChain的.h和.m文件,并添加Security.framework框架
+ (NSString *)getDeviceId{    
NSString * currentDeviceUUIDStr = [SSKeychain passwordForService:@" "account:@"uuid"];
   if(currentDeviceUUIDStr == nil || [currentDeviceUUIDStr isEqualToString:@""]) {
      NSUUID * currentDeviceUUID  = [UIDevice currentDevice].identifierForVendor;        
      currentDeviceUUIDStr = currentDeviceUUID.UUIDString;        
      currentDeviceUUIDStr = [currentDeviceUUIDStr stringByReplacingOccurrencesOfString:@"-"withString:@""];        
      currentDeviceUUIDStr = [currentDeviceUUIDStr lowercaseString];        
      [SSKeychainsetPassword: currentDeviceUUIDStrforService:@" "account:@"uuid"];    
   }
   return currentDeviceUUIDStr;
}

五十六. 獲取設備型號

//引入頭文件
#include #include

+ (NSString *)getCurrentDeviceModel{    
   int mib[2];    
   size_t len;    
   char *machine;        
   mib[0] = CTL_HW;    
   mib[1] = HW_MACHINE;    
   sysctl(mib, 2, NULL, &len, NULL, 0);    
   machine = malloc(len);    
   sysctl(mib, 2, machine, &len, NULL, 0);        
   NSString *platform = [NSString stringWithCString:machine encoding:NSASCIIStringEncoding];    
   free(machine);    
//iPhone 
if([platform isEqualToString:@"iPhone1,1"])return@"iPhone2G";
if([platform isEqualToString:@"iPhone1,2"])return@"iPhone3G";
if([platform isEqualToString:@"iPhone2,1"])return@"iPhone3GS";
if([platform isEqualToString:@"iPhone3,1"])return@"iPhone4";
if([platform isEqualToString:@"iPhone3,2"])return@"iPhone4";
if([platform isEqualToString:@"iPhone3,3"])return@"iPhone4";
if([platform isEqualToString:@"iPhone4,1"])return@"iPhone4S";
if([platform isEqualToString:@"iPhone5,1"])return@"iPhone5";
if([platform isEqualToString:@"iPhone5,2"])return@"iPhone5";
if([platform isEqualToString:@"iPhone5,3"])return@"iPhone5c";
if([platform isEqualToString:@"iPhone5,4"])return@"iPhone5c";
if([platform isEqualToString:@"iPhone6,1"])return@"iPhone5s";
if([platform isEqualToString:@"iPhone6,2"])return@"iPhone5s";
if([platform isEqualToString:@"iPhone7,2"])return@"iPhone6";
if([platform isEqualToString:@"iPhone7,1"])return@"iPhone6Plus";
if([platform isEqualToString:@"iPhone8,1"])return@"iPhone6s";
if([platform isEqualToString:@"iPhone8,2"])return@"iPhone6sPlus";
if([platform isEqualToString:@"iPhone8,3"])return@"iPhoneSE";
if([platform isEqualToString:@"iPhone8,4"])return@"iPhoneSE";
if([platform isEqualToString:@"iPhone9,1"])return@"iPhone7";
if([platform isEqualToString:@"iPhone9,2"])return@"iPhone7Plus";

 //iPod Touch
if([platform isEqualToString:@"iPod1,1"])return@"iPodTouch";
if([platform isEqualToString:@"iPod2,1"])return@"iPodTouch2G";
if([platform isEqualToString:@"iPod3,1"])return@"iPodTouch3G";
if([platform isEqualToString:@"iPod4,1"])return@"iPodTouch4G";
if([platform isEqualToString:@"iPod5,1"])return@"iPodTouch5G";
if([platform isEqualToString:@"iPod7,1"])return@"iPodTouch6G";    

//iPad 
if([platform isEqualToString:@"iPad1,1"])return@"iPad";
if([platform isEqualToString:@"iPad2,1"])return@"iPad2";
if([platform isEqualToString:@"iPad2,2"])return@"iPad2";
if([platform isEqualToString:@"iPad2,3"])return@"iPad2";
if([platform isEqualToString:@"iPad2,4"])return@"iPad2";
if([platform isEqualToString:@"iPad3,1"])return@"iPad3";
if([platform isEqualToString:@"iPad3,2"])return@"iPad3";
if([platform isEqualToString:@"iPad3,3"])return@"iPad3";
if([platform isEqualToString:@"iPad3,4"])return@"iPad4";
if([platform isEqualToString:@"iPad3,5"])return@"iPad4";
if([platform isEqualToString:@"iPad3,6"])return@"iPad4";  

//iPad Air 
if([platform isEqualToString:@"iPad4,1"])return@"iPadAir";
if([platform isEqualToString:@"iPad4,2"])return@"iPadAir";
if([platform isEqualToString:@"iPad4,3"])return@"iPadAir";
if([platform isEqualToString:@"iPad5,3"])return@"iPadAir2";
if([platform isEqualToString:@"iPad5,4"])return@"iPadAir2";        

//iPad mini
if([platform isEqualToString:@"iPad2,5"])return@"iPadmini1G";
if([platform isEqualToString:@"iPad2,6"])return@"iPadmini1G";
if([platform isEqualToString:@"iPad2,7"])return@"iPadmini1G";
if([platform isEqualToString:@"iPad4,4"])return@"iPadmini2";
if([platform isEqualToString:@"iPad4,5"])return@"iPadmini2";
if([platform isEqualToString:@"iPad4,6"])return@"iPadmini2";
if([platform isEqualToString:@"iPad4,7"])return@"iPadmini3";
if([platform isEqualToString:@"iPad4,8"])return@"iPadmini3";
if([platform isEqualToString:@"iPad4,9"])return@"iPadmini3";
if([platform isEqualToString:@"iPad5,1"])return@"iPadmini4";
if([platform isEqualToString:@"iPad5,2"])return@"iPadmini4";
if([platform isEqualToString:@"i386"])return@"iPhoneSimulator";
if([platform isEqualToString:@"x86_64"])return@"iPhoneSimulator";
return platform;
}

五十七. 減少發布之后過多的NSLog帶來的性能影響

#if defined(DEBUG)||defined(_DEBUG)NSLog(@"測試代碼");  
NSLog(@"Test Coding");
#endif

五十八. 去掉字符串的前后空格(基本用在textfield)

NSString *textName = [self.nameCell.textField.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];

五十九. 截取字符串到指定字符的位置

NSString *string = @"abcdefghijklmn";
NSRange range = [string rangeOfString:@"h"];
string = [string substringToIndex:range.location];

六十. 獲取label的行數和每行的內容

- (NSArray *)getLinesArrayOfStringInLabel:(UILabel *)label {    
   NSString *text = [label text];    
   UIFont *font = [label font];    
   CGRect rect = [label frame];    
   CTFontRef myFont = CTFontCreateWithName(( CFStringRef)([font fontName]), [font pointSize], NULL);    
   NSMutableAttributedString *attStr = [[NSMutableAttributedString alloc] initWithString:text];    
   [attStr addAttribute:(NSString *)kCTFontAttributeName value:(__bridge  id)myFont range:NSMakeRange(0, attStr.length)];    
   CFRelease(myFont);    
   CTFramesetterRef frameSetter = CTFramesetterCreateWithAttributedString(( CFAttributedStringRef)attStr);    
   CGMutablePathRef path = CGPathCreateMutable();    CGPathAddRect(path, NULL, CGRectMake(0,0,rect.size.width,100000));    
   CTFrameRef frame = CTFramesetterCreateFrame(frameSetter, CFRangeMake(0, 0), path, NULL);    
   NSArray *lines = ( NSArray *)CTFrameGetLines(frame); 
   NSMutableArray *linesArray = [[NSMutableArray alloc]init];
   for(id lineinlines) {        
      CTLineRef lineRef = (__bridge  CTLineRef )line;        
      CFRange lineRange = CTLineGetStringRange(lineRef);    
      NSRange range = NSMakeRange(lineRange.location, lineRange.length);        
      NSString *lineString = [text substringWithRange:range];           CFAttributedStringSetAttribute((CFMutableAttributedStringRef)attStr, lineRange, kCTKernAttributeName, (CFTypeRef)([NSNumber numberWithFloat:0.0]));    
      CFAttributedStringSetAttribute((CFMutableAttributedStringRef)attStr, lineRange, kCTKernAttributeName, (CFTypeRef)([NSNumber numberWithInt:0.0]));        
//   NSLog(@"''''''''''''''''''%@",lineString);        
      [linesArray addObject:lineString];    
   }    
   CGPathRelease(path);    
   CFRelease( frame );    
   CFRelease(frameSetter);
   return(NSArray *)linesArray;
}

六十一.鍵盤透明

[UITextField alloc].keyboardAppearance = UIKeyboardAppearanceAlert;

六十二.狀態欄的網絡活動風火輪是否旋轉,默認為NO

[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;

六十三.開啟右滑返回

self.navigationController.interactivePopGestureRecognizer.delegete = nil;

六十四.MD5加密

#import "NSString+MD5.h"#import

- (NSString *)stringToMD5:(NSString *)str {
//1.首先將字符串轉換成UTF-8編碼, 因為MD5加密是基于C語言的,所以要先把字符串轉化成C語言的字符串    
   const char *fooData = [str UTF8String];
//2.然后創建一個字符串數組,接收MD5的值    
   unsigned char result[CC_MD5_DIGEST_LENGTH];
//3.計算MD5的值, 這是官方封裝好的加密方法:把我們輸入的字符串轉換成16進制的32位數,然后存儲到result中    
   CC_MD5(fooData, (CC_LONG)strlen(fooData), result);    
/**    第一個參數:要加密的字符串    第二個參數: 獲取要加密字符串的長度    第三個參數: 接收結果的數組    */
//4.創建一個字符串保存加密結果    
   NSMutableString *saveResult = [NSMutableString string];
//5.從result 數組中獲取加密結果并放到 saveResult中 
   for (int i = 0; i < CC_MD5_DIGEST_LENGTH; i++) {        
      [saveResult appendFormat:@"%02x", result];    
   }    
/** x表示十六進制,%02X  意思是不足兩位將用0補齊,如果多余兩位則不影響        
NSLog("%02X", 0x888);  
//888        
NSLog("%02X", 0x4); 
//04    
*/
return saveResult;}

六十五.導航欄返回按鈕顏色設置 及 文字變成<

-(void)UIBarButtonBackItemSet{    
[[UIBarButtonItem appearance]setBackButtonTitlePositionAdjustment:UIOffsetMake(0, -60)forBarMetrics:UIBarMetricsDefault];
self.navigationController.navigationBar.barStyle = UIStatusBarStyleDefault;   
[self.navigationController.navigationBarsetTintColor:[UIColor whiteColor]];}

六十六.字符串中包含雙引號和反斜杠處理

NSString *testStr = @"你好,\"你好\"";  
NSLog(@"%@",testStr);  
//輸出結果為:你好,"你好"
NSString *testStr = @"不好,\\不好\\\\"; 
NSLog(@"%@",testStr);
//輸出結果為:不好,\不好\\
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容