ios 工作經驗總結

1 播放一張張連續的圖片,例如刷新動畫

/ 加入現在有三張圖片分別為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];
// 方法二解釋下,這個方法會加載animate_為前綴的,后邊0-1024,也就是animate_0、animate_1一直到animate_1024

2 tableView 使用總結

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

3 讓導航控制器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 
  //默認
else if(orientation == UIInterfaceOrientationPortrait)
  //豎屏
else if(orientation == UIInterfaceOrientationLandscapeLeft)
  // 左橫屏
else if(orientation == UIInterfaceOrientationLandscapeRight)
  //右橫屏

5 監聽scrollView是否滾動到了頂部/底部

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

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

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 單個頁面多個網絡請求的情況,需要監聽所有網絡請求結束后刷新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
            });
        });
    });
//利用線程組

7 頁面跳轉實現翻轉動畫

// 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];

8 獲取字符串中的數字

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

9 某個界面多個事件同時響應引起的問題, (比如點擊過快, push 了兩個頁面)


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

// 或者只設置button
[[UIButton appearance] setExclusiveTouch:YES];

10 禁止手機睡眠

[UIApplication sharedApplication].idleTimerDisabled = YES;

11獲取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;
}

12 清理app緩存

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

13 AFNetworking監聽網絡狀態

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

14 獲取一個視頻的第一幀圖片

 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 獲取視頻的時長

+ (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某個角添加圓角

// 左上角和右下角添加圓角
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 將一個view放置在其兄弟視圖的最上面

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

19 讓手機震動一下

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

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

//  最好抽成一個分類
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 在狀態欄增加網絡請求的菊花,類似safari加載網頁的時候狀態欄菊花

[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;

22 將一個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);
        }
    }];
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容

  • Android 自定義View的各種姿勢1 Activity的顯示之ViewRootImpl詳解 Activity...
    passiontim閱讀 173,373評論 25 708
  • 發現 關注 消息 iOS 第三方庫、插件、知名博客總結 作者大灰狼的小綿羊哥哥關注 2017.06.26 09:4...
    肇東周閱讀 12,245評論 4 61
  • 單張圖片緩存思路先把圖片緩存到本地,再獲取圖片大小 (GCD調度組監聽下載完成) 單張圖片緩存進入加載微博列表視圖...
    DavidFeng_swift閱讀 191評論 0 1
  • 礽哥兒坐著會哦哦對話了,雖然嗓音嘶啞,像卡著痰,一點不像小孩子。 一直咬我。 能拿的動安撫小海馬了,激動地啊啊叫。...
    礽哥兒閱讀 154評論 0 0