iOS--小知識點(持續更新)

黑白灰的綠i發表於2017-12-13

####一. 顏色漸變

 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];
    
    [copymutablearray setObject:@"加入到第一位" 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];
    [paragraphStyle setLineSpacing: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);
複製程式碼

十. 生成手機唯一ID:UUID

-(NSString*) uuid {
    CFUUIDRef puuid = CFUUIDCreate( nil );
    CFStringRef uuidString = CFUUIDCreateString( nil, puuid );
    NSString * result = (NSString *)CFBridgingRelease(CFStringCreateCopy( NULL, uuidString));
    CFRelease(puuid);
    CFRelease(uuidString);
    return result;
}
複製程式碼

十一. label自適應高度

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

十二. 使用AFN判斷網路狀態

 NSURL *url=[NSURL URLWithString:@"http://www.apple.com"];
    AFHTTPRequestOperationManager *operationManager=[[AFHTTPRequestOperationManager alloc]initWithBaseURL:url];
    //根據不同的網路狀態改變去做相應處理
    [operationManager.reachabilityManager setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
               switch (status) {
            case AFNetworkReachabilityStatusReachableViaWWAN:
                [self fasongsuoyou];
                break;
            case AFNetworkReachabilityStatusReachableViaWiFi:
                       [self fasongsuoyou];
                break;
            case AFNetworkReachabilityStatusNotReachable:
                [self alert:NSLocalizedString(@"wuwangluo",@"")];
                break;
            default:
                break;
        }
    }];
    //開始監控
    [operationManager.reachabilityManager startMonitoring];
複製程式碼

十三. image轉換成data型別

NSData *data=UIImagePNGRepresentation(image);
NSData *data=UIImageJPEGRepresentation(image, 1.0);
複製程式碼

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

//當前時間
NSDate *  senddate=[NSDate date];
        NSDateFormatter  *dateformatter=[[NSDateFormatter alloc] init];
        [dateformatter setDateFormat:@"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];
    [dateFormatter setDateFormat:@"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:color forKey: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 要執行的view
 *  @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 = [CAMediaTimingFunction functionWithName: @"easeInEaseOut"];
    [changeOutView.layer addAnimation:animation forKey: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;// 右偏10
    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){ [a doSomething]; }; 對於這種在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;
 [b doSomethingWithFinishBlock:^{ weakSelf.text = @"記憶體檢測"; [weakSelf doSomething]; }];
複製程式碼

二十七. 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種:
        //1.當我們的手離開螢幕時候隱藏
    - (void)scrollViewWillEndDragging:(UIScrollView *)scrollView withVelocity:(CGPoint)velocity targetContentOffset:(inout CGPoint *)targetContentOffset
    { 
        if(velocity.y > 0) 
        {
        [self.navigationController setNavigationBarHidden:YES animated:YES];
        } else {
        [self.navigationController setNavigationBarHidden: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.tabBar setBackgroundImage:img];
    [self.tabBar setShadowImage:img];
    //[self.navigationController.navigationBar setBackgroundImage: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]) {
            return NO;
        }
        return YES;
    }
複製程式碼

三十四. 獲取當前連線的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 *controller in self.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來捕獲上下文的資訊 官方文件

四十二. 使應用在後臺執行

- (void)applicationDidEnterBackground:(UIApplication *)application  
{  
    __block UIBackgroundTaskIdentifier bgTask = UIBackgroundTaskInvalid;  
    bgTask = [application beginBackgroundTaskWithExpirationHandler:^{  
        dispatch_async(dispatch_get_main_queue(), ^{  
            if (bgTask != UIBackgroundTaskInvalid) {  
                bgTask = UIBackgroundTaskInvalid;  
            }  
        });  
    }];  
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{  
        dispatch_async(dispatch_get_main_queue(), ^{  
            if (bgTask != UIBackgroundTaskInvalid) {  
                bgTask = UIBackgroundTaskInvalid;  
            }  
        });  
    });  
}  
複製程式碼

但其實不是應用一直在執行。

四十三. 計算一段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 *fontfamilyname in [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.tableView setSeparatorInset:UIEdgeInsetsMake(0,0,0,0)];
}
if ([self.tableView respondsToSelector:@selector(setLayoutMargins:)]) 
{
[self.tableView setLayoutMargins:UIEdgeInsetsMake(0,0,0,0)]; 
}
}
-(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath{
if ([cell respondsToSelector:@selector(setSeparatorInset:)]) 
{
[cell setSeparatorInset:UIEdgeInsetsZero]; 
} 
if ([cell respondsToSelector:@selector(setLayoutMargins:)]) 
{
[cell setLayoutMargins:UIEdgeInsetsZero]; 
}
}
複製程式碼

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

textField.placeholder = @"username is in here!";  
[textField setValue:[UIColor redColor] forKeyPath:@"_placeholderLabel.textColor"];  
[textField setValue:[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") {
      [alertController setValue:alertControllerStr forKey:@"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") {
      [alertController setValue:alertControllerMessageStr forKey:@"attributedMessage"];
  }
//修改按鈕字型顏色
UIAlertAction *defaultAction = [UIAlertAction actionWithTitle:@"Default" style:UIAlertActionStyleDefault handler:nil];
[alertController addAction:defaultAction];
 if (cancelAction valueForKey:@"titleTextColor") {
      [cancelAction setValue:[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];
        [SSKeychain setPassword: currentDeviceUUIDStr forService:@" "account:@"uuid"];
    }
    return currentDeviceUUIDStr;
}
複製程式碼

五十六. 獲取裝置型號

引入標頭檔案

#include <sys/types.h> #include <sys/sysctl.h>

+ (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 line in lines) {
        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.delegate = nil; 
複製程式碼

六十四.MD5加密

#import "NSString+MD5.h"
#import <CommonCrypto/CommonCrypto.h>
複製程式碼
- (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.navigationBar setTintColor:[UIColor whiteColor]];
}
複製程式碼

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

NSString * testStr = @"你好,\"你好\"";  
NSLog(@"%@",testStr);  

//輸出結果為:你好,"你好"

 NSString * testStr = @"不好,\\不好\\\\";
 NSLog(@"%@",testStr);

//輸出結果為:不好,\不好\\
複製程式碼
                                  ##待續!!複製程式碼

相關文章