ios 工作經(jīng)驗(yàn)總結(jié)

1 播放一張張連續(xù)的圖片,例如刷新動(dòng)畫

/ 加入現(xiàn)在有三張圖片分別為animate_1、animate_2、animate_3
// 方法一
    imageView.animationImages = @[[UIImage imageNamed:@"animate_1"], [UIImage imageNamed:@"animate_2"], [UIImage imageNamed:@"animate_3"]];
imageView.animationDuration = 1.0;
// 方法二
    imageView.image = [UIImage animatedImageNamed:@"animate_" duration:1.0];
// 方法二解釋下,這個(gè)方法會(huì)加載animate_為前綴的,后邊0-1024,也就是animate_0、animate_1一直到animate_1024

2 tableView 使用總結(jié)

得到當(dāng)前tableView顯示的 cell 數(shù)組
NSArray *cells = [self.tableView visibleCells];
// 判斷某一行的cell是否已經(jīng)顯示
CGRect cellRect = [tableView rectForRowAtIndexPath:indexPath];
BOOL completelyVisible = CGRectContainsRect(tableView.bounds, cellRect);
//tableView 自動(dòng)滑動(dòng)到某一行
 //第一種方法
[tableView scrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewScrollPositionTop animated:YES];
//第二種方法
[self.tableVieW selectRowAtIndexPath:indexPath animated:YES scrollPosition:UITableViewScrollPositionTop];

3 讓導(dǎo)航控制器pop回指定的控制器

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

4 獲取屏幕方向

UIInterfaceOrientation orientation = [UIApplication sharedApplication].statusBarOrientation;

if(orientation == 0) //Default orientation 
  //默認(rèn)
else if(orientation == UIInterfaceOrientationPortrait)
  //豎屏
else if(orientation == UIInterfaceOrientationLandscapeLeft)
  // 左橫屏
else if(orientation == UIInterfaceOrientationLandscapeRight)
  //右橫屏

5 監(jiān)聽scrollView是否滾動(dòng)到了頂部/底部

-(void)scrollViewDidScroll: (UIScrollView*)scrollView
{
    float scrollViewHeight = scrollView.frame.size.height;
    float scrollContentSizeHeight = scrollView.contentSize.height;
    float scrollOffset = scrollView.contentOffset.y;

    if (scrollOffset == 0)
    {
        // 滾動(dòng)到了頂部
    }
    else if (scrollOffset + scrollViewHeight == scrollContentSizeHeight)
    {
        // 滾動(dòng)到了底部
    }
}

5 MD5加密

+ (NSString *)md5:(NSString *)str
{
    const char *concat_str = [str UTF8String];
    unsigned char result[CC_MD5_DIGEST_LENGTH];
    CC_MD5(concat_str, (unsigned int)strlen(concat_str), result);
    NSMutableString *hash = [NSMutableString string];
    for (int i =0; i <16; i++){
        [hash appendFormat:@"%02X", result[i]];
    }
    return [hash uppercaseString];
}

6 單個(gè)頁面多個(gè)網(wǎng)絡(luò)請求的情況,需要監(jiān)聽所有網(wǎng)絡(luò)請求結(jié)束后刷新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, ^{
        // 網(wǎng)絡(luò)請求一
        [WebClick getDataSuccess:^(ResponseModel *model) {
            dispatch_group_leave(group);
        } failure:^(NSString *err) {
            dispatch_group_leave(group);
        }];
    });
    dispatch_group_enter(group);
    dispatch_group_async(group, serialQueue, ^{
        // 網(wǎng)絡(luò)請求二
        [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, ^{
        // 網(wǎng)絡(luò)請求三
        [WebClick getDataSuccess:^{
            dispatch_group_leave(group);
        } failure:^(NSString *errorString) {
            dispatch_group_leave(group);
        }];
    });

    // 所有網(wǎng)絡(luò)請求結(jié)束后會(huì)來到這個(gè)方法
    dispatch_group_notify(group, serialQueue, ^{
        dispatch_async(dispatch_get_global_queue(0, 0), ^{
            dispatch_async(dispatch_get_main_queue(), ^{
                // 刷新UI
            });
        });
    });
//利用線程組

7 頁面跳轉(zhuǎn)實(shí)現(xiàn)翻轉(zhuǎn)動(dòng)畫

// modal方式(模態(tài))
    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];

8 獲取字符串中的數(shù)字

- (NSString *)getNumberFromStr:(NSString *)str
{
    NSCharacterSet *nonDigitCharacterSet = [[NSCharacterSet decimalDigitCharacterSet] invertedSet];
    return [[str componentsSeparatedByCharactersInSet:nonDigitCharacterSet] componentsJoinedByString:@""];
 NSLog(@"%@", [self getNumberFromStr:@"12a0b05c1d2e3f4fda8fa8fad9fsad23"]);
 // 12005123488923
}

9 某個(gè)界面多個(gè)事件同時(shí)響應(yīng)引起的問題, (比如點(diǎn)擊過快, push 了兩個(gè)頁面)


// 一個(gè)一個(gè)設(shè)置太麻煩了,可以全局設(shè)置
[[UIView appearance] setExclusiveTouch:YES];

// 或者只設(shè)置button
[[UIButton appearance] setExclusiveTouch:YES];

10 禁止手機(jī)睡眠

[UIApplication sharedApplication].idleTimerDisabled = YES;

11獲取app緩存大小

- (CGFloat)getCachSize {

    NSUInteger imageCacheSize = [[SDImageCache sharedImageCache] getSize];
    //獲取自定義緩存大小
    //用枚舉器遍歷 一個(gè)文件夾的內(nèi)容
    //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;//自定義所有緩存大小
    }
    // 得到是字節(jié)  轉(zhuǎn)化為M
    CGFloat totalSize = ((CGFloat)imageCacheSize+count)/1024/1024;
    return totalSize;
}

12 清理app緩存

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

13 AFNetworking監(jiān)聽網(wǎng)絡(luò)狀態(tài)

   AFNetworkReachabilityManager *mgr = [AFNetworkReachabilityManager sharedManager];
    [mgr setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
        switch (status) {
            case AFNetworkReachabilityStatusUnknown:
                break;
            case AFNetworkReachabilityStatusNotReachable: {
                [SVProgressHUD showInfoWithStatus:@"當(dāng)前設(shè)備無網(wǎng)絡(luò)"];
            }
                break;
            case AFNetworkReachabilityStatusReachableViaWiFi:
                [SVProgressHUD showInfoWithStatus:@"當(dāng)前Wi-Fi網(wǎng)絡(luò)"];
                break;
            case AFNetworkReachabilityStatusReachableViaWWAN:
                [SVProgressHUD showInfoWithStatus:@"當(dāng)前蜂窩移動(dòng)網(wǎng)絡(luò)"];
                break;
            default:
                break;
        }
    }];
    

14 獲取一個(gè)視頻的第一幀圖片

 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;

15 獲取視頻的時(shí)長

+ (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;
}

16 刪除NSUserDefaults所有記錄

NSString *appDomain = [[NSBundle mainBundle] bundleIdentifier];
 [[NSUserDefaults standardUserDefaults] removePersistentDomainForName:appDomain]; 

17 為UIView某個(gè)角添加圓角

// 左上角和右下角添加圓角
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;

18 將一個(gè)view放置在其兄弟視圖的最上面

[parentView bringSubviewToFront:yourView]
// 將一個(gè)view放置在其兄弟視圖的最下面
[parentView sendSubviewToBack:yourView]

19 讓手機(jī)震動(dòng)一下

  導(dǎo)入框架
#import <AudioToolbox/AudioToolbox.h>
AudioServicesPlayAlertSound(kSystemSoundID_Vibrate);
或者
AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);

20 在非ViewController的地方彈出UIAlertController對話框

//  最好抽成一個(gè)分類
UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"Title" message:@"message" preferredStyle:UIAlertControllerStyleAlert];
//...
id rootViewController = [UIApplication sharedApplication].delegate.window.rootViewController;
if([rootViewController isKindOfClass:[UINavigationController class]])
{
    rootViewController = ((UINavigationController *)rootViewController).viewControllers.firstObject;
}
if([rootViewController isKindOfClass:[UITabBarController class]])
{
    rootViewController = ((UITabBarController *)rootViewController).selectedViewController;
}
[rootViewController presentViewController:alertController animated:YES completion:nil];

21 在狀態(tài)欄增加網(wǎng)絡(luò)請求的菊花,類似safari加載網(wǎng)頁的時(shí)候狀態(tài)欄菊花

[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;

22 將一個(gè)image保存在相冊中

import <Photos/Photos.h>
[[PHPhotoLibrary sharedPhotoLibrary] performChanges:^{
        PHAssetChangeRequest *changeRequest = [PHAssetChangeRequest creationRequestForAssetFromImage:image];
        changeRequest.creationDate          = [NSDate date];
    } completionHandler:^(BOOL success, NSError *error) {
        if (success) {
            NSLog(@"successfully saved");
        }
        else {
            NSLog(@"error saving to photos: %@", error);
        }
    }];
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • Android 自定義View的各種姿勢1 Activity的顯示之ViewRootImpl詳解 Activity...
    passiontim閱讀 179,063評論 25 709
  • 發(fā)現(xiàn) 關(guān)注 消息 iOS 第三方庫、插件、知名博客總結(jié) 作者大灰狼的小綿羊哥哥關(guān)注 2017.06.26 09:4...
    肇東周閱讀 15,380評論 4 61
  • 芝麻餅alian閱讀 1,018評論 1 1
  • 單張圖片緩存思路先把圖片緩存到本地,再獲取圖片大小 (GCD調(diào)度組監(jiān)聽下載完成) 單張圖片緩存進(jìn)入加載微博列表視圖...
    DavidFeng_swift閱讀 253評論 0 1
  • 礽哥兒坐著會(huì)哦哦對話了,雖然嗓音嘶啞,像卡著痰,一點(diǎn)不像小孩子。 一直咬我。 能拿的動(dòng)安撫小海馬了,激動(dòng)地啊啊叫。...
    礽哥兒閱讀 170評論 0 0

友情鏈接更多精彩內(nèi)容