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

####一. 顏色漸變html

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它。ios

二十六. 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)/工程地址, 這樣寫的好處可使你的挪動代碼不用手動更換路徑!c++

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

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來捕獲上下文的信息 官方文檔git

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

- (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 便可bash

五十. 解決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;
}
複製代碼

五十六. 獲取設備型號

引入頭文件app

#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);

//輸出結果爲:很差,\很差\\
複製代碼
##待續!!複製代碼
相關文章
相關標籤/搜索