1. 程式人生 > >iOS 各種方法

iOS 各種方法

eof des mas read pdo lds csg skin lex

tableViewCell分割線左對齊:

- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
    [cell setSeparatorInset:UIEdgeInsetsZero];
    [cell setLayoutMargins:UIEdgeInsetsZero];
    cell.preservesSuperviewLayoutMargins = NO;
}

- (void
)viewDidLayoutSubviews { [self.tableView setSeparatorInset:UIEdgeInsetsZero]; [self.tableView setLayoutMargins:UIEdgeInsetsZero]; }

單個頁面多個網絡請求的情況,需要監聽所有網絡請求結束後刷新UI:

dispatch_group_t group = dispatch_group_create();
    dispatch_queue_t serialQueue = dispatch_queue_create("com.wzb.test.www"
, DISPATCH_QUEUE_SERIAL); dispatch_group_enter(group); dispatch_group_async(group, serialQueue, ^{ // 網絡請求一 [WebClick getDataSuccess:^(ResponseModel *model) { dispatch_group_leave(group); } failure:^(NSString *err) { dispatch_group_leave(group); }]; }); dispatch_group_enter(group); dispatch_group_async(group, serialQueue,
^{ // 網絡請求二 [WebClick getDataSuccess:getBigTypeRM onSuccess:^(ResponseModel *model) { dispatch_group_leave(group); } failure:^(NSString *errorString) { dispatch_group_leave(group); }]; }); dispatch_group_enter(group); dispatch_group_async(group, serialQueue, ^{ // 網絡請求三 [WebClick getDataSuccess:^{ dispatch_group_leave(group); } failure:^(NSString *errorString) { dispatch_group_leave(group); }]; }); // 所有網絡請求結束後會來到這個方法 dispatch_group_notify(group, serialQueue, ^{ dispatch_async(dispatch_get_global_queue(0, 0), ^{ dispatch_async(dispatch_get_main_queue(), ^{ // 刷新UI }); }); });

獲取一個類的所有屬性:

id PersonClass = objc_getClass("Person");
unsigned int outCount, i;
objc_property_t *properties = class_copyPropertyList(PersonClass, &outCount);
for (i = 0; i < outCount; i++) {
    objc_property_t property = properties[i];
    fprintf(stdout, "%s %s\n", property_getName(property), property_getAttributes(property));
}

獲取手機和app信息:

NSDictionary *infoDictionary = [[NSBundle mainBundle] infoDictionary];  
 CFShow(infoDictionary);  
// app名稱  
 NSString *app_Name = [infoDictionary objectForKey:@"CFBundleDisplayName"];  
 // app版本  
 NSString *app_Version = [infoDictionary objectForKey:@"CFBundleShortVersionString"];  
 // app build版本  
 NSString *app_build = [infoDictionary objectForKey:@"CFBundleVersion"];  



    //手機序列號  
    NSString* identifierNumber = [[UIDevice currentDevice] uniqueIdentifier];  
    NSLog(@"手機序列號: %@",identifierNumber);  
    //手機別名: 用戶定義的名稱  
    NSString* userPhoneName = [[UIDevice currentDevice] name];  
    NSLog(@"手機別名: %@", userPhoneName);  
    //設備名稱  
    NSString* deviceName = [[UIDevice currentDevice] systemName];  
    NSLog(@"設備名稱: %@",deviceName );  
    //手機系統版本  
    NSString* phoneVersion = [[UIDevice currentDevice] systemVersion];  
    NSLog(@"手機系統版本: %@", phoneVersion);  
    //手機型號  
    NSString* phoneModel = [[UIDevice currentDevice] model];  
    NSLog(@"手機型號: %@",phoneModel );  
    //地方型號  (國際化區域名稱)  
    NSString* localPhoneModel = [[UIDevice currentDevice] localizedModel];  
    NSLog(@"國際化區域名稱: %@",localPhoneModel );  

    NSDictionary *infoDictionary = [[NSBundle mainBundle] infoDictionary];  
    // 當前應用名稱  
    NSString *appCurName = [infoDictionary objectForKey:@"CFBundleDisplayName"];  
    NSLog(@"當前應用名稱:%@",appCurName);  
    // 當前應用軟件版本  比如:1.0.1  
    NSString *appCurVersion = [infoDictionary objectForKey:@"CFBundleShortVersionString"];  
    NSLog(@"當前應用軟件版本:%@",appCurVersion);  
    // 當前應用版本號碼   int類型  
    NSString *appCurVersionNum = [infoDictionary objectForKey:@"CFBundleVersion"];  
    NSLog(@"當前應用版本號碼:%@",appCurVersionNum);

修改textField的placeholder的字體顏色、大小:

[textField setValue:[UIColor redColor] forKeyPath:@"_placeholderLabel.textColor"];
[textField setValue:[UIFont boldSystemFontOfSize:16] forKeyPath:@"_placeholderLabel.font"];

獲取沙盒 Document:

#define PathDocument [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject]

獲取沙盒 Cache:

#define PathCache [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) firstObject]

顏色轉圖片:

+ (UIImage *)creatImageWithColor:(UIColor *)color {
  CGRect rect = CGRectMake(0.0f, 0.0f, 1.0f, 1.0f);
  UIGraphicsBeginImageContext(rect.size);
  CGContextRef context = UIGraphicsGetCurrentContext();

  CGContextSetFillColorWithColor(context, [color CGColor]);
  CGContextFillRect(context, rect);

  UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
  UIGraphicsEndImageContext();

  return image;
}

獲取app緩存大小:

- (CGFloat)getCachSize {

    NSUInteger imageCacheSize = [[SDImageCache sharedImageCache] getSize];
    //獲取自定義緩存大小
    //用枚舉器遍歷 一個文件夾的內容
    //1.獲取 文件夾枚舉器
    NSString *myCachePath = [NSHomeDirectory() stringByAppendingPathComponent:@"Library/Caches"];
    NSDirectoryEnumerator *enumerator = [[NSFileManager defaultManager] enumeratorAtPath:myCachePath];
    __block NSUInteger count = 0;
    //2.遍歷
    for (NSString *fileName in enumerator) {
        NSString *path = [myCachePath stringByAppendingPathComponent:fileName];
        NSDictionary *fileDict = [[NSFileManager defaultManager] attributesOfItemAtPath:path error:nil];
        count += fileDict.fileSize;//自定義所有緩存大小
    }
    // 得到是字節  轉化為M
    CGFloat totalSize = ((CGFloat)imageCacheSize+count)/1024/1024;
    return totalSize;
}

清理app緩存:

- (void)handleClearView {
    //刪除兩部分
    //1.刪除 sd 圖片緩存
    //先清除內存中的圖片緩存
    [[SDImageCache sharedImageCache] clearMemory];
    //清除磁盤的緩存
    [[SDImageCache sharedImageCache] clearDisk];
    //2.刪除自己緩存
    NSString *myCachePath = [NSHomeDirectory() stringByAppendingPathComponent:@"Library/Caches"];
    [[NSFileManager defaultManager] removeItemAtPath:myCachePath error:nil];
}

去除數組中重復的對象:

方法一:

NSArray * arr1 = @[@1,@2,@3];
    
    NSArray * arr2 = @[@2,@3,@4,@5];
    
    NSPredicate * filterPredicate = [NSPredicate predicateWithFormat:@"NOT (SELF IN %@)",arr1];
    
    NSArray * filter = [arr2 filteredArrayUsingPredicate:filterPredicate];
    NSLog(@"%@",filter);


方法二:


NSArray *newArr = [oldArr valueForKeyPath:@[email protected]"];

打印百分號和引號:

    NSLog(@"%%");
    NSLog(@"\"");

幾個常用權限判斷:

if ([CLLocationManager authorizationStatus] ==kCLAuthorizationStatusDenied) {
        NSLog(@"沒有定位權限");
    }
    AVAuthorizationStatus statusVideo = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
    if (statusVideo == AVAuthorizationStatusDenied) {
        NSLog(@"沒有攝像頭權限");
    }
    //是否有麥克風權限
    AVAuthorizationStatus statusAudio = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeAudio];
    if (statusAudio == AVAuthorizationStatusDenied) {
        NSLog(@"沒有錄音權限");
    }
    [PHPhotoLibrary requestAuthorization:^(PHAuthorizationStatus status) {
        if (status == PHAuthorizationStatusDenied) {
            NSLog(@"沒有相冊權限");
        }
    }];

image拉伸:

+ (UIImage *)resizableImage:(NSString *)imageName
{
    UIImage *image = [UIImage imageNamed:imageName];
    CGFloat imageW = image.size.width;
    CGFloat imageH = image.size.height;
    return [image resizableImageWithCapInsets:UIEdgeInsetsMake(imageH * 0.5, imageW * 0.5, imageH * 0.5, imageW * 0.5) resizingMode:UIImageResizingModeStretch];
}

JSON字符串轉字典:

+ (NSDictionary *)parseJSONStringToNSDictionary:(NSString *)JSONString {
    NSData *JSONData = [JSONString dataUsingEncoding:NSUTF8StringEncoding];
    NSDictionary *responseJSON = [NSJSONSerialization JSONObjectWithData:JSONData options:NSJSONReadingMutableLeaves error:nil];
    return responseJSON;
}

一個字符串是否包含另一個字符串:

// 方法1
if ([str1 containsString:str2]) {
        NSLog(@"str1包含str2");
    } else {
        NSLog(@"str1不包含str2");
    }

// 方法2
if ([str1 rangeOfString: str2].location == NSNotFound) {
        NSLog(@"str1不包含str2");
    } else {
        NSLog(@"str1包含str2");
    }

cell去除選中效果:

cell.selectionStyle = UITableViewCellSelectionStyleNone;

cell點按效果:

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}

判斷字符串中是否有空格:

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

移除字符串中的空格和換行:

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

約束如何做UIView動畫?

1、把需要改的約束Constraint拖條線出來,成為屬性
2、在需要動畫的地方加入代碼,改變此屬性的constant屬性
3、開始做UIView動畫,動畫裏邊調用layoutIfNeeded方法

@property (weak, nonatomic) IBOutlet NSLayoutConstraint *buttonTopConstraint;
self.buttonTopConstraint.constant = 100;
    [UIView animateWithDuration:.5 animations:^{
        [self.view layoutIfNeeded];
    }];

刪除NSUserDefaults所有記錄:

//方法一
  NSString *appDomain = [[NSBundle mainBundle] bundleIdentifier];
 [[NSUserDefaults standardUserDefaults] removePersistentDomainForName:appDomain];   
 //方法二  
- (void)resetDefaults {   
  NSUserDefaults * defs = [NSUserDefaults standardUserDefaults];
     NSDictionary * dict = [defs dictionaryRepresentation];
     for (id key in dict) {
          [defs removeObjectForKey:key];
     }
      [defs synchronize];
 }
// 方法三
[[NSUserDefaults standardUserDefaults] setPersistentDomain:[NSDictionary dictionary] forName:[[NSBundle mainBundle] bundleIdentifier]];

自定義cell選中背景顏色:

UIView *bgColorView = [[UIView alloc] init];
bgColorView.backgroundColor = [UIColor redColor];
[cell setSelectedBackgroundView:bgColorView];

layoutSubviews方法什麽時候調用?

1、init方法不會調用
2、addSubview方法等時候會調用
3、bounds改變的時候調用
4、scrollView滾動的時候會調用scrollView的layoutSubviews方法(所以不建議在scrollView的layoutSubviews方法中做復雜邏輯)
5、旋轉設備的時候調用
6、子視圖被移除的時候調用

修改UISegmentedControl的字體大小:

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

獲取一個view所屬的控制器:

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

UIImage和base64互轉:

- (NSString *)encodeToBase64String:(UIImage *)image {
 return [UIImagePNGRepresentation(image) base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength];
}

- (UIImage *)decodeBase64ToImage:(NSString *)strEncodeData {
  NSData *data = [[NSData alloc]initWithBase64EncodedString:strEncodeData options:NSDataBase64DecodingIgnoreUnknownCharacters];
  return [UIImage imageWithData:data];
}

設置tableView分割線顏色:

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

不讓控制器的view隨著控制器的xib拉伸或壓縮:

self.view.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;

修改cell.imageView的大小:

UIImage *icon = [UIImage imageNamed:@""];
CGSize itemSize = CGSizeMake(30, 30);
UIGraphicsBeginImageContextWithOptions(itemSize, NO ,0.0);
CGRect imageRect = CGRectMake(0.0, 0.0, itemSize.width, itemSize.height);
[icon drawInRect:imageRect];
cell.imageView.image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();

設置UILabel行間距:

NSMutableAttributedString* attrString = [[NSMutableAttributedString  alloc] initWithString:label.text];
    NSMutableParagraphStyle *style = [[NSMutableParagraphStyle alloc] init];
    [style setLineSpacing:20];
    [attrString addAttribute:NSParagraphStyleAttributeName value:style range:NSMakeRange(0, label.text.length)];
    label.attributedText = attrString;

UILabel顯示不同顏色字體:

NSMutableAttributedString * string = [[NSMutableAttributedString alloc] initWithString:label.text];
[string addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:NSMakeRange(0,5)];
[string addAttribute:NSForegroundColorAttributeName value:[UIColor greenColor] range:NSMakeRange(5,6)];
[string addAttribute:NSForegroundColorAttributeName value:[UIColor blueColor] range:NSMakeRange(11,5)];
label.attributedText = string;

比較兩個NSDate相差多少小時:

NSDate* date1 = someDate;
 NSDate* date2 = someOtherDate;
 NSTimeInterval distanceBetweenDates = [date1 timeIntervalSinceDate:date2];
 double secondsInAnHour = 3600;
// 除以3600是把秒化成小時,除以60得到結果為相差的分鐘數
 NSInteger hoursBetweenDates = distanceBetweenDates / secondsInAnHour;

每個cell之間增加間距:

// 自定義cell,重寫setFrame:方法
- (void)setFrame:(CGRect)frame
{
    frame.size.height -= 20;
    [super setFrame:frame];
}

加載gif圖片:

推薦使用這個框架 FLAnimatedImage

保存UIImage到本地:

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *filePath = [[paths objectAtIndex:0] stringByAppendingPathComponent:@"Image.png"];

[UIImagePNGRepresentation(image) writeToFile:filePath atomically:YES];

讓導航控制器pop回指定的控制器:

NSMutableArray *allViewControllers = [NSMutableArray arrayWithArray:[self.navigationController viewControllers]];
for (UIViewController *aViewController in allViewControllers) {
    if ([aViewController isKindOfClass:[RequiredViewController class]]) {
        [self.navigationController popToViewController:aViewController animated:NO];
    }
}

地圖上兩個點之間的實際距離:

// 需要導入#import <CoreLocation/CoreLocation.h>
CLLocation *locA = [[CLLocation alloc] initWithLatitude:34 longitude:113];
    CLLocation *locB = [[CLLocation alloc] initWithLatitude:31.05 longitude:121.76];
// CLLocationDistance求出的單位為米
    CLLocationDistance distance = [locA distanceFromLocation:locB];

字符串encode編碼(編碼url字符串不成功的問題):

// 我們一般用這個方法處理stringByAddingPercentEscapesUsingEncoding但是這個方法好想不會處理/和&這種特殊符號,這種情況就需要用下邊這個方法處理
@implementation NSString (NSString_Extended)
- (NSString *)urlencode {
    NSMutableString *output = [NSMutableString string];
    const unsigned char *source = (const unsigned char *)[self UTF8String];
    int sourceLen = strlen((const char *)source);
    for (int i = 0; i < sourceLen; ++i) {
        const unsigned char thisChar = source[i];
        if (thisChar ==  ){
            [output appendString:@"+"];
        } else if (thisChar == . || thisChar == - || thisChar == _ || thisChar == ~ || 
                   (thisChar >= a && thisChar <= z) ||
                   (thisChar >= A && thisChar <= Z) ||
                   (thisChar >= 0 && thisChar <= 9)) {
            [output appendFormat:@"%c", thisChar];
        } else {
            [output appendFormat:@"%%%02X", thisChar];
        }
    }
    return output;
}

通知監聽APP生命周期:

UIApplicationDidEnterBackgroundNotification 應用程序進入後臺
UIApplicationWillEnterForegroundNotification 應用程序將要進入前臺
UIApplicationDidFinishLaunchingNotification 應用程序完成啟動
UIApplicationDidFinishLaunchingNotification 應用程序由掛起變的活躍
UIApplicationWillResignActiveNotification 應用程序掛起(有電話進來或者鎖屏)
UIApplicationDidReceiveMemoryWarningNotification 應用程序收到內存警告
UIApplicationDidReceiveMemoryWarningNotification 應用程序終止(後臺殺死、手機關機等)
UIApplicationSignificantTimeChangeNotification 當有重大時間改變(淩晨0點,設備時間被修改,時區改變等)
UIApplicationWillChangeStatusBarOrientationNotification 設備方向將要改變
UIApplicationDidChangeStatusBarOrientationNotification 設備方向改變
UIApplicationWillChangeStatusBarFrameNotification 設備狀態欄frame將要改變
UIApplicationDidChangeStatusBarFrameNotification 設備狀態欄frame改變
UIApplicationBackgroundRefreshStatusDidChangeNotification 應用程序在後臺下載內容的狀態發生變化
UIApplicationProtectedDataWillBecomeUnavailable 本地受保護的文件被鎖定,無法訪問
UIApplicationProtectedDataWillBecomeUnavailable 本地受保護的文件可用了

解決openUrl延時問題:

// 方法一
dispatch_async(dispatch_get_main_queue(), ^{

    UIApplication *application = [UIApplication sharedApplication];
    if ([application respondsToSelector:@selector(openURL:options:completionHandler:)]) {
        [application openURL:URL options:@{}
           completionHandler:nil];
    } else {
        [application openURL:URL];
    }
    });
// 方法二
[self performSelector:@selector(redirectToURL:) withObject:url afterDelay:0.1];

- (void) redirectToURL
{
UIApplication *application = [UIApplication sharedApplication];
    if ([application respondsToSelector:@selector(openURL:options:completionHandler:)]) {
        [application openURL:URL options:@{}
           completionHandler:nil];
    } else {
        [application openURL:URL];
    }
}

頁面跳轉實現翻轉動畫:

// modal方式
    TestViewController *vc = [[TestViewController alloc] init];
    vc.view.backgroundColor = [UIColor redColor];
    vc.modalTransitionStyle = UIModalTransitionStyleCoverVertical;
    [self presentViewController:vc animated:YES completion:nil];

// push方式
    TestViewController *vc = [[TestViewController alloc] init];
    vc.view.backgroundColor = [UIColor redColor];
    [UIView beginAnimations:@"View Flip" context:nil];
    [UIView setAnimationDuration:0.80];
    [UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];
    [UIView setAnimationTransition:UIViewAnimationTransitionFlipFromRight forView:self.navigationController.view cache:NO];
    [self.navigationController pushViewController:vc animated:YES];
    [UIView commitAnimations];

使用xib設置UIView的邊框、圓角:

技術分享

修改tabBar的frame:

- (void)viewWillLayoutSubviews {

    CGRect tabFrame = self.tabBar.frame;
    tabFrame.size.height = 100;
    tabFrame.origin.y = self.view.frame.size.height - 100;
    self.tabBar.frame = tabFrame;
}

iOS 各種方法