iOS開發小技巧合集

本文主要記錄平常工做中積累的一些iOS小技巧

  • SDWebImage 加載大量高清圖片時內存暴增web

    • 解決方案:關閉SD加載高清大圖時的解壓縮
static BOOL SDImageCacheOldShouldDecompressImages = YES; 

static BOOL SDImagedownloderOldShouldDecompressImages = YES; 

- (void)viewDidLoad { 

  [super viewDidLoad]; 
  // 關閉SD加載高清大圖時的解壓縮 
  
  SDImageCache *canche = [SDImageCache sharedImageCache]; 
  
  SDImageCacheOldShouldDecompressImages = canche.shouldDecompressImages; 
  
  canche.shouldDecompressImages = NO; 
  
  SDWebImageDownloader *downloder = [SDWebImageDownloader sharedDownloader]; 
  
  SDImagedownloderOldShouldDecompressImages = downloder.shouldDecompressImages; 
 
  downloder.shouldDecompressImages = NO; 
 
 } 
 
 -(void)dealloc { 
 
 SDImageCache *canche = [SDImageCache sharedImageCache]; 
 
 canche.shouldDecompressImages = SDImageCacheOldShouldDecompressImages; 
 
 SDWebImageDownloader *downloder = [SDWebImageDownloader sharedDownloader]; 
 
 downloder.shouldDecompressImages = SDImagedownloderOldShouldDecompressImages; 
 
 }
  • SDWebImage本地緩存有時候會害人。若是以前緩存過一張圖片,即便下次服務器換了這張圖片,可是圖片url沒換,用SDWebimage下載下來的仍是之前那張,因此遇到這種問題,不要先去懟服務器,清空下緩存再試就行了。
  • 禁止手機睡眠
[UIApplication sharedApplication].idleTimerDisabled = YES;
  • 隱藏某行cell
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
// 若是是你須要隱藏的那一行,返回高度爲0

    if(indexPath.row == YouWantToHideRow){
       return 0;
    }
       return 44;
}

// 而後再你須要隱藏cell的時候調用
[self.tableView beginUpdates];
[self.tableView endUpdates];
  • 禁用button高亮
button.adjustsImageWhenHighlighted = NO;
或者在建立的時候
UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
  • 動畫切換window的根控制器
[UIView transitionWithView:[UIApplication sharedApplication].keyWindow duration:.5f 
options:UIViewAnimationOptionTransitionCrossDissolve animations:^{
        BOOL oldState = [UIView areAnimationsEnabled];
        [UIView setAnimationsEnabled:NO];
        [UIApplication sharedApplication].keyWindow.rootViewController = [[RootViewController alloc]init];
        [UIView setAnimationsEnabled:oldState];
    } completion:^(BOOL finished) {

    }];
  • 去除數組中重複的對象
NSArray *newArr = [oldArr valueForKeyPath:@"@distinctUnionOfObjects.self"];
  • 編譯的時候遇到 no such file or directory: /users/apple/XXXwindows

    • 是由於編譯的時候,在此路徑下找不到這個文件,解決這個問題,首先是是要檢查缺乏的文件是否是在工程中,若是不在工程中,須要從本地拖進去,若是發現已經存在工程中了,或者拖進去仍是報錯,這時候須要去build phases中搜索這個文件,這時候極可能會搜出現兩個相同的文件,這時候,有一個路徑是正確的,刪除另一個便可。若是刪除了仍是不行,須要把兩個都刪掉,而後從新往工程裏拖進這個文件便可
  • iOS8系統中,tableView最好實現下-tableView: heightForRowAtIndexPath:這個代理方法,要否則在iOS8中可能就會出現顯示不全或者沒法響應事件的問題
  • iOS8中實現側滑功能的時候這個方法必須實現,要否則在iOS8中沒法側滑
// 必須寫的方法,和editActionsForRowAtIndexPath配對使用,裏面什麼不寫也行
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {

}
  • 三個比較特殊的通知
NSSystemTimeZoneDidChangeNotification監聽修改時間界面的兩個按鈕狀態變化

UIApplicationSignificantTimeChangeNotification 監聽用戶改變時間 (只要點擊自動設置按鈕就會調用)

NSSystemClockDidChangeNotification 監聽用戶修改時間(時間不一樣纔會調用)
  • 獲取不到UICollectionView指定cell的問題
[self.collectionView layoutIfNeeded];//添加這句話就好 

QTMResContinueEditeCell *cell = (QTMResContinueEditeCell *)[self.collectionView cellForItemAtIndexPath:[NSIndexPath indexPathForItem:_index inSection:0]];
  • 跳進app權限設置
// 跳進app設置
if (UIApplicationOpenSettingsURLString != NULL) {
    UIApplication *application = [UIApplication sharedApplication];
    NSURL *URL = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
    if ([application respondsToSelector:@selector(openURL:options:completionHandler:)]) {
        [application openURL:URL options:@{}
           completionHandler:nil];
    } else {
        [application openURL:URL];
    }
}
  • 給一個view截圖
- (UIImage *)cutImageWithView:(UIView *)view
{
    UIGraphicsBeginImageContextWithOptions(view.frame.size, NO, 0);
    [view.layer renderInContext:UIGraphicsGetCurrentContext()];
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    return image;
}
  • 注意對象爲nil的時候,調用此對象分類的方法不會執行
  • collectionView的內容小於其寬高的時候是不能滾動的,設置能夠滾動:
collectionView.alwaysBounceHorizontal = YES;

collectionView.alwaysBounceVertical = YES;
  • 顏色轉圖片
+ (UIImage *)imageWithColor:(UIColor *)color {

    //描述一個矩形
    CGRect rect = CGRectMake(0.0f, 0.0f, 1.0f, 1.0f);
    //開啓圖形上下文
    UIGraphicsBeginImageContextWithOptions(rect.size, NO, 0);

    //得到圖形上下文
    CGContextRef ctx = UIGraphicsGetCurrentContext();

    //使用color演示填充上下文
    CGContextSetFillColorWithColor(ctx, [color CGColor]);

    //渲染上下文
    CGContextFillRect(ctx, rect);

    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();

    //關閉圖形上下文
    UIGraphicsEndImageContext();
    
    return image;
    
}
  • view設置圓角
#define ViewBorderRadius(View, Radius, Width, Color)\
\
[View.layer setCornerRadius:(Radius)];\
[View.layer setMasksToBounds:YES];\
[View.layer setBorderWidth:(Width)];\
[View.layer setBorderColor:[Color CGColor]] // view圓角
  • view某個角度設置圓角
UIBezierPath *maskPath = [UIBezierPath bezierPathWithRoundedRect:self.whiteView.bounds byRoundingCorners:UIRectCornerTopLeft | UIRectCornerTopRight cornerRadii:CGSizeMake(10, 10)];
    CAShapeLayer *maskLayer = [[CAShapeLayer alloc] init];
    maskLayer.frame = self.whiteView.bounds;
    maskLayer.path = maskPath.CGPath;
    self.whiteView.layer.mask = maskLayer;
    
  ##指定了須要成爲圓角的角該參數是UIRectCorner類型的,可選的值有:
* UIRectCornerTopLeft
* UIRectCornerTopRight
* UIRectCornerBottomLeft
* UIRectCornerBottomRight
* UIRectCornerAllCorners
  • 由角度轉換弧度
#define DegreesToRadian(x) (M_PI * (x) / 180.0)
  • 由弧度轉換角度
#define RadianToDegrees(radian) (radian*180.0)/(M_PI)
  • 獲取圖片資源
//建議使用前兩種宏定義,性能高於後者

#define LOADIMAGE(file,ext) [UIImage imageWithContentsOfFile:[[NSBundle mainBundle]pathForResource:file ofType:ext]]

#define IMAGE(A) [UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:A ofType:nil]]

#define ImageNamed(_pointer) [UIImage imageNamed:[UIUtil imageName:_pointer]]

#define UIImageName(name) [UIImage imageNamed:name]
  • 文件路徑
//獲取temp
#define PathTemp NSTemporaryDirectory()

//獲取Document
#define PathDocument [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject]

//獲取 Cache
#define PathCache [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) firstObject]
  • GCD代碼只執行一次
#define kDISPATCH_ONCE_BLOCK(onceBlock) static dispatch_once_t onceToken; 
dispatch_once(&onceToken, onceBlock);
  • 自定義NSLog
//DEBUG  模式下打印日誌,當前行
#ifdef DEBUG
#   define DLog(fmt, ...) NSLog((@"%s [Line %d] " fmt), __PRETTY_FUNCTION__, __LINE__, ##__VA_ARGS__);
#else
#   define DLog(...)
#endif


//重寫NSLog,Debug模式下打印日誌和當前行數
#if DEBUG
#define NSLog(FORMAT, ...) fprintf(stderr,"\nfunction:%s line:%d content:%s\n", __FUNCTION__, __LINE__, [[NSString stringWithFormat:FORMAT, ##__VA_ARGS__] UTF8String]);
#else
#define NSLog(FORMAT, ...) nil
#endif

//DEBUG  模式下打印日誌,當前行 並彈出一個警告
#ifdef DEBUG
#   define ULog(fmt, ...)  { UIAlertView *alert = [[UIAlertView alloc] initWithTitle:[NSString stringWithFormat:@"%s\n [Line %d] ", __PRETTY_FUNCTION__, __LINE__] message:[NSString stringWithFormat:fmt, ##__VA_ARGS__]  delegate:nil cancelButtonTitle:@"Ok" otherButtonTitles:nil]; [alert show]; }
#else
#   define ULog(...)
#endif
  • Font
#define FONTS(size) [UIFont systemFontOfSize:(size)]
#define BOLDFONTS(size) [UIFont boldSystemFontOfSize:(size)]
  • GCD
//主線程
#define kDISPATCH_MAIN_THREAD(mainQueueBlock) dispatch_async(dispatch_get_main_queue(), mainQueueBlock);

//異步線程
#define kDISPATCH_GLOBAL_QUEUE_DEFAULT(globalQueueBlock) dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), globalQueueBlocl);
  • 通知
#define NOTIF_ADD(n, f)     [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(f) name:n object:nil]
#define NOTIF_POST(n, o)    [[NSNotificationCenter defaultCenter] postNotificationName:n object:o]
#define NOTIF_REMV()        [[NSNotificationCenter defaultCenter] removeObserver:self]
  • Color
// RGB顏色轉換(16進制->10進制)
#define UIColorFromRGB(rgbValue) [UIColor colorWithRed:((float)((rgbValue & 0xFF0000) >> 16))/255.0 green:((float)((rgbValue & 0xFF00) >> 8))/255.0 blue:((float)(rgbValue & 0xFF))/255.0 alpha:1.0]

// 獲取RGB顏色
#define RGBA(r,g,b,a) [UIColor colorWithRed:r/255.0f green:g/255.0f blue:b/255.0f alpha:a]

//清除背景色
#define CLEARCOLOR [UIColor clearColor]

// 隨機色
#define RandomCOLOR RGBCOLOR(arc4random_uniform(256),arc4random_uniform(256),arc4random_uniform(256))
  • 獲取window
+(UIWindow*)getWindow {
    UIWindow* win = nil; //[UIApplication sharedApplication].keyWindow;
    for (id item in [UIApplication sharedApplication].windows) {
        if ([item class] == [UIWindow class]) {
            if (!((UIWindow*)item).hidden) {
                win = item;
                break;
            }
        }
    }
    return win;
}
  • 修改textField的placeholder的字體顏色、大小
[textField setValue:[UIColor redColor] forKeyPath:@"_placeholderLabel.textColor"];
[textField setValue:[UIFont boldSystemFontOfSize:16] forKeyPath:@"_placeholderLabel.font"];
// 或者
textField.attributedPlaceholder = [[NSAttributedString alloc] initWithString:placeholder attributes:@{NSFontAttributeName : [UIFont systemFontOfSize:13],NSForegroundColorAttributeName : [UIColor grayColor]}];
  • APP緩存
/** *  存 數組數據*/
+(void)setObectOfArray:(NSArray *)array fileName:(NSString *)fileName
{
    
    //緩存文件的 根路徑
    NSString *path = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) firstObject];
    // 緩存 文件夾 路徑
    NSString *filePath = [path stringByAppendingPathComponent:@"XXX.dataCache"];
    
    NSFileManager *fileManager = [NSFileManager defaultManager];
    
    if ([fileManager fileExistsAtPath:filePath] == NO)
    {
        [fileManager createDirectoryAtPath:filePath withIntermediateDirectories:YES attributes:nil error:nil];
    }
    //緩存文件的路徑
    NSString * cacheFilePath = [filePath stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.plist",fileName]];
    BOOL isSuccess = [array writeToFile:cacheFilePath atomically:NO];
    if (isSuccess) {
        NSLog(@"緩存數據成功:---%@",cacheFilePath);
    }else
    {
        NSLog(@"緩存數據失敗:---%@",cacheFilePath);
    }
    
}

/***  取 數組數據*/
+(NSArray *)cacheArrayForFileName:(NSString *)fileName
{
    
    //緩存文件的 根路徑
    NSString *path = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) firstObject];
    // 緩存 文件夾 路徑
    NSString *filePath = [path stringByAppendingPathComponent:@"XXX.dataCache"];
    //緩存文件的路徑
    NSString * cacheFilePath = [filePath stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.plist",fileName]];
    //取得緩存文件
    NSArray *array  = [NSArray arrayWithContentsOfFile:cacheFilePath];
    
    return array;
}

/*** 清除 這個所有的緩存數據 */
+(void)clearCacheListData:(void (^)())completion
{
    // 異線程
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        // 清楚緩存
        //緩存文件的 根路徑
        NSString *path = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) firstObject];
        // 緩存 文件夾 路徑
        NSString *filePath = [path stringByAppendingPathComponent:@"FortuneDonkey.dataCache"];
        NSFileManager *manager = [NSFileManager defaultManager];
        //移除文件夾
        [manager removeItemAtPath:filePath error:nil];
        //  建立一個新的文件夾
        [manager createDirectoryAtPath:filePath withIntermediateDirectories:YES attributes:nil error:nil];
        if (completion)
        {
            //回調主線程
            dispatch_async(dispatch_get_main_queue(), ^{
                completion();
            });
        }
    });
}

/*** 清除SD緩存數據 */
-(void)clearSDCacheData
{
    //先清除內存中的圖片緩存
    [[SDImageCache sharedImageCache] clearMemory];
    //清除磁盤的緩存
    [[SDImageCache sharedImageCache] clearDisk];
}
  • 獲取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;
}
  • 幾個經常使用權限判斷
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(@"沒有相冊權限");
        }
    }];
  • 系統相關的一些方法
//獲取系統版本
#define IOS_VERSION [[[UIDevice currentDevice] systemVersion] floatValue]
#define IS_IOS10_OR_LATER    ([[[UIDevice currentDevice] systemVersion] floatValue] >= 10.0)

//獲取當前語言
#define CurrentLanguage ([[NSLocale preferredLanguages] objectAtIndex:0])

//判斷是否 Retina屏、設備是否%fhone 五、是不是iPad
#define isRetina ([UIScreen instancesRespondToSelector:@selector(currentMode)] ? CGSizeEqualToSize(CGSizeMake(640, 960), [[UIScreen mainScreen] currentMode].size) : NO)
#define iPhone5 ([UIScreen instancesRespondToSelector:@selector(currentMode)] ? CGSizeEqualToSize(CGSizeMake(640, 1136), [[UIScreen mainScreen] currentMode].size) : NO)
#define iPhone6 ([UIScreen instancesRespondToSelector:@selector(currentMode)] ? CGSizeEqualToSize(CGSizeMake(750, 1334), [[UIScreen mainScreen] currentMode].size) : NO)
#define isPad (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)

//判斷是真機仍是模擬器
#if TARGET_OS_IPHONE
//iPhone Device
#endif

#if TARGET_IPHONE_SIMULATOR
//iPhone Simulator
#endif
  • 長按複製功能
- (void)viewDidLoad
{
    [self.view addGestureRecognizer:[[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(pasteBoard:)]];
}
- (void)pasteBoard:(UILongPressGestureRecognizer *)longPress {
    if (longPress.state == UIGestureRecognizerStateBegan) {
        UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
        pasteboard.string = @"我是文字";
    }
}
  • 判斷圖片類型
//經過圖片 Data 數據第一個字節 來獲取圖片擴展名
- (NSString *)contentTypeForImageData:(NSData *)data
{
    uint8_t c;
    [data getBytes:&c length:1];
    switch (c)
    {
        case 0xFF:
            return @"jpeg";

        case 0x89:
            return @"png";

        case 0x47:
            return @"gif";

        case 0x49:
        case 0x4D:
            return @"tiff";

        case 0x52:
        if ([data length] < 12) {
            return nil;
        }

        NSString *testString = [[NSString alloc] initWithData:[data subdataWithRange:NSMakeRange(0, 12)] encoding:NSASCIIStringEncoding];
        if ([testString hasPrefix:@"RIFF"]
            && [testString hasSuffix:@"WEBP"])
        {
            return @"webp";
        }

        return nil;
    }

    return nil;
}
  • 獲取手機和 APP 信息
//手機序列號
NSString* identifierNumber = [[UIDevice currentDevice] uniqueIdentifier];

//手機別名: 用戶定義的名稱
NSString* userPhoneName = [[UIDevice currentDevice] name];

//設備名稱
NSString* deviceName = [[UIDevice currentDevice] systemName];

//手機系統版本
NSString* phoneVersion = [[UIDevice currentDevice] systemVersion];

//手機型號
NSString* phoneModel = [[UIDevice currentDevice] model];

//地方型號  (國際化區域名稱)
NSString* localPhoneModel = [[UIDevice currentDevice] localizedModel];

NSDictionary *infoDictionary = [[NSBundle mainBundle] infoDictionary];
// 當前應用名稱
NSString *appCurName = [infoDictionary objectForKey:@"CFBundleDisplayName"];

// 當前應用版本  
NSString *appCurVersion = [infoDictionary objectForKey:@"CFBundleShortVersionString"];

// 當前應用版本號碼   int類型
NSString *appCurVersionNum = [infoDictionary objectForKey:@"CFBundleVersion"];
  • UIImage繪製圓角
- (UIImage *)circleImage
{
    // NO表明透明
    UIGraphicsBeginImageContextWithOptions(self.size, NO, 1);
    // 得到上下文
    CGContextRef ctx = UIGraphicsGetCurrentContext();
    // 添加一個圓
    CGRect rect = CGRectMake(0, 0, self.size.width, self.size.height);
    // 方形變圓形
    CGContextAddEllipseInRect(ctx, rect);
    // 裁剪
    CGContextClip(ctx);
    // 將圖片畫上去
    [self drawInRect:rect];
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return image;
}
  • 準確獲取圖片像素
CGFloat fixelW = CGImageGetWidth(image.CGImage);
CGFloat fixelH = CGImageGetHeight(image.CGImage);
  • JSON字符串轉字典
+ (NSDictionary *)parseJSONStringToNSDictionary:(NSString *)JSONString {
    NSData *JSONData = [JSONString dataUsingEncoding:NSUTF8StringEncoding];
    NSDictionary *responseJSON = [NSJSONSerialization JSONObjectWithData:JSONData options:NSJSONReadingMutableLeaves error:nil];
    return responseJSON;
}
  • 獲取當前控制器
//獲取當前屏幕顯示的viewcontroller
- (UIViewController *)getCurrentVC{
    UIWindow *window = [[UIApplication sharedApplication].windows firstObject];
    if (!window) {
        return nil;
    }
    UIView *tempView;
    for (UIView *subview in window.subviews) {
        if ([[subview.classForCoder description] isEqualToString:@"UILayoutContainerView"]) {
            tempView = subview;
            break;
        }
    }
    if (!tempView) {
        tempView = [window.subviews lastObject];
    }
    
    id nextResponder = [tempView nextResponder];
    while (![nextResponder isKindOfClass:[UIViewController class]] || [nextResponder isKindOfClass:[UINavigationController class]] || [nextResponder isKindOfClass:[UITabBarController class]]) {
        tempView =  [tempView.subviews firstObject];
        
        if (!tempView) {
            return nil;
        }
        nextResponder = [tempView nextResponder];
    }
    return  (UIViewController *)nextResponder;
}
  • KVO監聽某個對象的屬性
// 添加監聽者
[self addObserver:self forKeyPath:property options:NSKeyValueObservingOptionNew context:nil];

// 當監聽的屬性值變化的時候會來到這個方法
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
    if ([keyPath isEqualToString:@"property"]) {
       [self textViewTextChange];
       } else {
     }
}
  • Reachability判斷網絡狀態
NetworkStatus status = [[Reachability reachabilityForInternetConnection] currentReachabilityStatus];
    if (status == NotReachable) {
        NSLog(@"當前設備無網絡");
    }
    if (status == ReachableViaWiFi) {
        NSLog(@"當前wifi網絡");
    }
    if (status == ReachableViaWWAN) {
        NSLog(@"當前蜂窩移動網絡");
    }
  • AFNetworking監聽網絡狀態
// 監聽網絡情況
    AFNetworkReachabilityManager *mgr = [AFNetworkReachabilityManager sharedManager];
    [mgr setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
        switch (status) {
            case AFNetworkReachabilityStatusUnknown:
                break;
            case AFNetworkReachabilityStatusNotReachable: {
                NSLog(@"當前設備無網絡");
            }
                break;
            case AFNetworkReachabilityStatusReachableViaWiFi:
                 NSLog(@"當前wifi網絡");
                break;
            case AFNetworkReachabilityStatusReachableViaWWAN:
                NSLog(@"當前蜂窩移動網絡");
                break;
            default:
                break;
        }
    }];
   [mgr startMonitoring];
  • 父視圖透明不影響子視圖的作法
self.view.backgroundColor = [[UIColor whiteColor]colorWithAlphaComponent:0.7f];
  • 取圖片某一點的顏色數組

    if (point.x < 0 || point.y < 0) return nil;
    
       CGImageRef imageRef = self.CGImage;
       NSUInteger width = CGImageGetWidth(imageRef);
       NSUInteger height = CGImageGetHeight(imageRef);
       if (point.x >= width || point.y >= height) return nil;
    
       unsigned char *rawData = malloc(height * width * 4);
       if (!rawData) return nil;
    
       CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
       NSUInteger bytesPerPixel = 4;
       NSUInteger bytesPerRow = bytesPerPixel * width;
       NSUInteger bitsPerComponent = 8;
       CGContextRef context = CGBitmapContextCreate(rawData,
                                                    width,
                                                    height,
                                                    bitsPerComponent,
                                                    bytesPerRow,
                                                    colorSpace,
                                                    kCGImageAlphaPremultipliedLast
                                                    | kCGBitmapByteOrder32Big);
       if (!context) {
           free(rawData);
           return nil;
       }
       CGColorSpaceRelease(colorSpace);
       CGContextDrawImage(context, CGRectMake(0, 0, width, height), imageRef);
       CGContextRelease(context);
    
       int byteIndex = (bytesPerRow * point.y) + point.x * bytesPerPixel;
       CGFloat red   = (rawData[byteIndex]     * 1.0) / 255.0;
       CGFloat green = (rawData[byteIndex + 1] * 1.0) / 255.0;
       CGFloat blue  = (rawData[byteIndex + 2] * 1.0) / 255.0;
       CGFloat alpha = (rawData[byteIndex + 3] * 1.0) / 255.0;
    
       UIColor *result = nil;
       result = [UIColor colorWithRed:red green:green blue:blue alpha:alpha];
       free(rawData);
       return result;
  • 判斷該圖片是否有透明度通道
- (BOOL)hasAlphaChannel
{
    CGImageAlphaInfo alpha = CGImageGetAlphaInfo(self.CGImage);
    return (alpha == kCGImageAlphaFirst ||
            alpha == kCGImageAlphaLast ||
            alpha == kCGImageAlphaPremultipliedFirst ||
            alpha == kCGImageAlphaPremultipliedLast);
}
  • 兩張圖片合成
+ (UIImage*)mergeImage:(UIImage*)firstImage withImage:(UIImage*)secondImage {
    CGImageRef firstImageRef = firstImage.CGImage;
    CGFloat firstWidth = CGImageGetWidth(firstImageRef);
    CGFloat firstHeight = CGImageGetHeight(firstImageRef);
    CGImageRef secondImageRef = secondImage.CGImage;
    CGFloat secondWidth = CGImageGetWidth(secondImageRef);
    CGFloat secondHeight = CGImageGetHeight(secondImageRef);
    CGSize mergedSize = CGSizeMake(MAX(firstWidth, secondWidth), MAX(firstHeight, secondHeight));
    UIGraphicsBeginImageContext(mergedSize);
    [firstImage drawInRect:CGRectMake(0, 0, firstWidth, firstHeight)];
    [secondImage drawInRect:CGRectMake(0, 0, secondWidth, secondHeight)];
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return image;
}
  • 製做水印
// 畫水印
- (void) setImage:(UIImage *)image withWaterMark:(UIImage *)mark inRect:(CGRect)rect
{
    if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 4.0)
    {
        UIGraphicsBeginImageContextWithOptions(self.frame.size, NO, 0.0);
    }
    //原圖
    [image drawInRect:self.bounds];
    //水印圖
    [mark drawInRect:rect];
    UIImage *newPic = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    self.image = newPic;
}
  • 讓label的文字內容顯示在左上/右上/左下/右下/中心頂/中心底部
自定義UILabel
// 重寫label的textRectForBounds方法
- (CGRect)textRectForBounds:(CGRect)bounds limitedToNumberOfLines:(NSInteger)numberOfLines {
    CGRect rect = [super textRectForBounds:bounds limitedToNumberOfLines:numberOfLines];
    switch (self.textAlignmentType) {
        case WZBTextAlignmentTypeLeftTop: {
            rect.origin = bounds.origin;
        }
            break;
        case WZBTextAlignmentTypeRightTop: {
            rect.origin = CGPointMake(CGRectGetMaxX(bounds) - rect.size.width, bounds.origin.y);
        }
            break;
        case WZBTextAlignmentTypeLeftBottom: {
            rect.origin = CGPointMake(bounds.origin.x, CGRectGetMaxY(bounds) - rect.size.height);
        }
            break;
        case WZBTextAlignmentTypeRightBottom: {
            rect.origin = CGPointMake(CGRectGetMaxX(bounds) - rect.size.width, CGRectGetMaxY(bounds) - rect.size.height);
        }
            break;
        case WZBTextAlignmentTypeTopCenter: {
            rect.origin = CGPointMake((CGRectGetWidth(bounds) - CGRectGetWidth(rect)) / 2, CGRectGetMaxY(bounds) - rect.origin.y);
        }
            break;
        case WZBTextAlignmentTypeBottomCenter: {
            rect.origin = CGPointMake((CGRectGetWidth(bounds) - CGRectGetWidth(rect)) / 2, CGRectGetMaxY(bounds) - CGRectGetMaxY(bounds) - rect.size.height);
        }
            break;
        case WZBTextAlignmentTypeLeft: {
            rect.origin = CGPointMake(0, rect.origin.y);
        }
            break;
        case WZBTextAlignmentTypeRight: {
            rect.origin = CGPointMake(rect.origin.x, 0);
        }
            break;
        case WZBTextAlignmentTypeCenter: {
            rect.origin = CGPointMake((CGRectGetWidth(bounds) - CGRectGetWidth(rect)) / 2, (CGRectGetHeight(bounds) - CGRectGetHeight(rect)) / 2);
        }
            break;

        default:
            break;
    }
    return rect;
}

- (void)drawTextInRect:(CGRect)rect {
    CGRect textRect = [self textRectForBounds:rect limitedToNumberOfLines:self.numberOfLines];
    [super drawTextInRect:textRect];
}
  • 移除字符串中的空格和換行
+ (NSString *)removeSpaceAndNewline:(NSString *)str {
    NSString *temp = [str stringByReplacingOccurrencesOfString:@" " withString:@""];
    temp = [temp stringByReplacingOccurrencesOfString:@"\r" withString:@""];
    temp = [temp stringByReplacingOccurrencesOfString:@"\n" withString:@""];
    return temp;
}
  • 判斷字符串中是否有空格
+ (BOOL)isBlank:(NSString *)str {
    NSRange _range = [str rangeOfString:@" "];
    if (_range.location != NSNotFound) {
        //有空格
        return YES;
    } else {
        //沒有空格
        return NO;
    }
}
  • 獲取一個視頻的第一幀圖片
NSURL *url = [NSURL URLWithString:filepath];
AVURLAsset *asset1 = [[AVURLAsset alloc] initWithURL:url options:nil];
AVAssetImageGenerator *generate1 = [[AVAssetImageGenerator alloc] initWithAsset:asset1];
generate1.appliesPreferredTrackTransform = YES;
NSError *err = NULL;
CMTime time = CMTimeMake(1, 2);
CGImageRef oneRef = [generate1 copyCGImageAtTime:time actualTime:NULL error:&err];
UIImage *one = [[UIImage alloc] initWithCGImage:oneRef];
 return one;
  • 獲取視頻的時長
+ (NSInteger)getVideoTimeByUrlString:(NSString *)urlString {
    NSURL *videoUrl = [NSURL URLWithString:urlString];
    AVURLAsset *avUrl = [AVURLAsset assetWithURL:videoUrl];
    CMTime time = [avUrl duration];
    int seconds = ceil(time.value/time.timescale);
    return seconds;
}
  • 當tableView佔不滿一屏時,去除下邊多餘的單元格
self.tableView.tableHeaderView = [UIView new];
self.tableView.tableFooterView = [UIView new];
  • isKindOfClass和isMemberOfClass的區別
isKindOfClass能夠判斷某個對象是否屬於某個類,或者這個類的子類。
isMemberOfClass更加精準,它只能判斷這個對象類型是否爲這個類(不能判斷子類)
  • 禁用系統滑動返回功能
- (void)viewDidAppear:(BOOL)animated
{
     [super viewDidAppear:animated];
     if ([self.navigationController respondsToSelector:@selector(interactivePopGestureRecognizer)]) 
     {self.navigationController.interactivePopGestureRecognizer.delegate = self;
    }
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    if ([self.navigationController respondsToSelector:@selector(interactivePopGestureRecognizer)]) 
    {self.navigationController.interactivePopGestureRecognizer.delegate = nil;
    }
}
- (BOOL)gestureRecognizerShouldBegin:(UIGestureRecognizer *)gestureRecognizer
{
     return NO;
}
  • UILabel設置內邊距
子類化UILabel,重寫drawTextInRect方法
- (void)drawTextInRect:(CGRect)rect {
    // 邊距,上左下右
    UIEdgeInsets insets = {0, 5, 0, 5};
    [super drawTextInRect:UIEdgeInsetsInsetRect(rect, insets)];
}
  • UILabel設置文字描邊
子類化UILabel,重寫drawTextInRect方法
- (void)drawTextInRect:(CGRect)rect
{
    CGContextRef c = UIGraphicsGetCurrentContext();
    // 設置描邊寬度
    CGContextSetLineWidth(c, 1);
    CGContextSetLineJoin(c, kCGLineJoinRound);
    CGContextSetTextDrawingMode(c, kCGTextStroke);
    // 描邊顏色
    self.textColor = [UIColor redColor];
    [super drawTextInRect:rect];
    // 文本顏色
    self.textColor = [UIColor yellowColor];
    CGContextSetTextDrawingMode(c, kCGTextFill);
    [super drawTextInRect:rect];
}
  • UIView背景顏色漸變
+ (CAGradientLayer *)setGradualChangingColor:(UIView *)view fromColor:(NSString *)fromHexColorStr toColor:(NSString *)toHexColorStr{
    //    CAGradientLayer類對其繪製漸變背景顏色、填充層的形狀(包括圓角)
    CAGradientLayer *gradientLayer = [CAGradientLayer layer];
    gradientLayer.frame = view.bounds;
    //  建立漸變色數組,須要轉換爲CGColor顏色
    gradientLayer.colors = @[(__bridge id)[UIColor colorWithHexString:fromHexColorStr].CGColor,(__bridge id)[UIColor colorWithHexString:toHexColorStr].CGColor];
    //  設置漸變顏色方向,左下點爲(0,0), 右上點爲(1,1)
    gradientLayer.startPoint = CGPointMake(0, 0.5);
    gradientLayer.endPoint = CGPointMake(1, 0.5);
    //  設置顏色變化點,取值範圍 0.0~1.0
    gradientLayer.locations = @[@0,@1];
    
    return gradientLayer;
}
  • UIView某個角添加圓角
// 左上角和右下角添加圓角
UIBezierPath *maskPath = [UIBezierPath bezierPathWithRoundedRect:view.bounds byRoundingCorners:(UIRectCornerTopLeft | UIRectCornerBottomRight) cornerRadii:CGSizeMake(20, 20)];
CAShapeLayer *maskLayer = [CAShapeLayer layer];
maskLayer.frame = view.bounds;
maskLayer.path = maskPath.CGPath;
view.layer.mask = maskLayer;
  • UIImage和base64互轉
// view分類方法
- (NSString *)encodeToBase64String:(UIImage *)image {
 return [UIImagePNGRepresentation(image) base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength];
}

- (UIImage *)decodeBase64ToImage:(NSString *)strEncodeData {
  NSData *data = [[NSData alloc]initWithBase64EncodedString:strEncodeData options:NSDataBase64DecodingIgnoreUnknownCharacters];
  return [UIImage imageWithData:data];
}
  • UIWebView設置背景透明
[webView setBackgroundColor:[UIColor clearColor]];
[webView setOpaque:NO];
  • 設置tableView分割線顏色以及頂到頭
// 分割線顏色
[self.tableView setSeparatorColor:[UIColor myColor]];

// 頂到頭
- (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];
}
  • 爲一個view添加虛線邊框
CAShapeLayer *border = [CAShapeLayer layer];
 border.strokeColor = [UIColor colorWithRed:67/255.0f green:37/255.0f blue:83/255.0f alpha:1].CGColor;
 border.fillColor = nil;
 border.lineDashPattern = @[@4, @2];
 border.path = [UIBezierPath bezierPathWithRect:view.bounds].CGPath;
 border.frame = view.bounds;
 [view.layer addSublayer:border];
  • UITextView中打開或禁用複製,剪切,選擇,全選等功能
// 繼承UITextView重寫這個方法
- (BOOL)canPerformAction:(SEL)action withSender:(id)sender
{
// 返回NO爲禁用,YES爲開啓
    // 粘貼
    if (action == @selector(paste:)) return NO;
    // 剪切
    if (action == @selector(cut:)) return NO;
    // 複製
    if (action == @selector(copy:)) return NO;
    // 選擇
    if (action == @selector(select:)) return NO;
    // 選中所有
    if (action == @selector(selectAll:)) return NO;
    // 刪除
    if (action == @selector(delete:)) return NO;
    // 分享
    if (action == @selector(share)) return NO;
    return [super canPerformAction:action withSender:sender];
}
相關文章
相關標籤/搜索