iOS开发小知识备忘录

作者: 随行的羊 | 来源:发表于2018-09-03 14:55 被阅读63次

    代码备忘:

    1、点击空白处,收起键盘

    UITapGestureRecognizer *tapGestureRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(hideKeyBoard)];
    tapGestureRecognizer.cancelsTouchesInView = NO;
    [self.tableView addGestureRecognizer:tapGestureRecognizer];
    
    - (void)hideKeyBoard {
    
        [self.textField endEditing:YES];
    }
    

    2、拨打电话

    NSString *phoneStr = @"telprompt:400-8888888";
    NSURL *url  =[NSURL URLWithString:phoneStr];
    [[UIApplication sharedApplication] openURL:url];
    

    3、web加载网址

    NSURLRequest *request = [[NSURLRequest alloc] initWithURL:[NSURL URLWithString:urlString]];
    [self.webView loadRequest:request];
    

    4、定时器定义

    - (NSTimer *)timer {
    
        if (_timer == nil) {
        
            _timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(timerFireMethod) userInfo:nil repeats:YES];
        }
    
        return _timer;
    }
    

    5、UICollectionView的代理和数据源

    #pragma mark - UICollectionViewDataSource
    
    - (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    
        return 1;
    }
    
    - (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    
        return 10;
    }
    
    - (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    
        UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"UICollectionViewCell" forIndexPath:indexPath];
    
        return cell;
    }
    
    #pragma mark - UICollectionViewDelegate
    
    - (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    
    
    }
    

    6、UITableView的代理和数据源

    #pragma mark - UITableViewDataSource
    
    - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    
        return 1;
    }
    
    - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
        return 10;
    }
    
    - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
        NSInteger row = indexPath.row;
        NSInteger section = indexPath.section;
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"UITableViewCell" forIndexPath:indexPath];
    
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
    
        return cell;
    }
    
    #pragma mark - UITableViewDelegates
    
    - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
        [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    }
    

    7、隐藏导航栏

    - (void)viewWillAppear:(BOOL)animated {
    
        [super viewWillAppear:animated];
    
        [self.navigationController setNavigationBarHidden:YES animated:animated];
    }
    
    - (void)viewWillDisappear:(BOOL)animated {
    
        [super viewWillDisappear:animated];
    
        [self.navigationController setNavigationBarHidden:NO animated:animated];
    }
    

    8、提示框

    self.loginTipAlertController = [UIAlertController alertControllerWithTitle:@"提示" message:@"" preferredStyle:UIAlertControllerStyleAlert];
    
        @weakify(self);
    
        UIAlertAction *loginAction = [UIAlertAction actionWithTitle:@"" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
        @strongify(self);
        
        [self testBack];
    }];
    
    UIAlertAction *returnPwdAction = [UIAlertAction actionWithTitle:@"" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
        @strongify(self);
        
        [self testReturnPwdControllerView];
    }];
    
    [self.loginTipAlertController addAction:loginAction];
    [self.loginTipAlertController addAction:returnPwdAction];
    [self presentViewController:self.loginTipAlertController animated:YES completion:nil];
    

    9、约束动画

    [UIView animateWithDuration:0.3 animations:^{
        
        [self.view layoutIfNeeded];
    }];
    

    10、代码执行时间

    CFAbsoluteTime startTime1 = CFAbsoluteTimeGetCurrent();
    ///……
    CFAbsoluteTime startTime2 = CFAbsoluteTimeGetCurrent();
    CFAbsoluteTime linkTime1 = (startTime2 - startTime1);
    NSLog(@"添加数据花费的时间为 in %f ms", linkTime1 * 1000.0);
    

    11、iOS 11及以上系统可用

    if (@available(iOS 11.0, *)) {
            
    }
    

    12、iOS系统判断

    #define iOS7Later ([UIDevice currentDevice].systemVersion.floatValue >= 7.0f)
    #define iOS8Later ([UIDevice currentDevice].systemVersion.floatValue >= 8.0f)
    #define iOS9Later ([UIDevice currentDevice].systemVersion.floatValue >= 9.0f)
    
    if ([[UIDevice currentDevice].systemVersion floatValue] >= 10.0) {
    
    }
    
    if ([[UIDevice currentDevice].systemVersion floatValue] >= 11.0) {
    
    }
    

    13、跳转到指定的控制器

    for (UIViewController *viewController in self.navigationController.childViewControllers) {
        
        if ([NSStringFromClass([viewController class]) isEqualToString:@"UIViewController"]) {
            
            [self.navigationController popToViewController:viewController animated:YES];
            
            break ;
        }
    }
    

    14、Debug环境下

    #ifdef DEBUG
    
    #endif
    

    15、将视图添加到UIWindow

    UIWindow *rootWindow = [UIApplication sharedApplication].keyWindow;
    [rootWindow addSubview:view];
    

    其他一些:

    1、通知的#define定义

    #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_POSTU(n, o, u)    [[NSNotificationCenter defaultCenter] postNotificationName:n object:o userInfo:u];
    #define NOTIF_REMVN(n)          [[NSNotificationCenter defaultCenter] removeObserver:self name:n object:nil];
    #define NOTIF_REMV()            [[NSNotificationCenter defaultCenter] removeObserver:self]
    

    2、只能输入数字

    NSCharacterSet *characterSet = [[NSCharacterSet characterSetWithCharactersInString:@"0123456789"] invertedSet];
    NSString *filtered = [[self.phoneTextField.text componentsSeparatedByCharactersInSet:characterSet] componentsJoinedByString:@""];
    self.phoneTextField.text = filtered;
    

    3、获取根导航控制器

    - (UINavigationController *)rootNavigationController {
    
        UITabBarController *tabBarController = nil;
        UINavigationController *navigation = nil;
        id rootViewController = [UIApplication sharedApplication].keyWindow.rootViewController;
        if ([rootViewController isKindOfClass:[UITabBarController class]]) {
        
            tabBarController = (UITabBarController *)[UIApplication sharedApplication].keyWindow.rootViewController;
            navigation = tabBarController.selectedViewController;
        
        } else if ([rootViewController isKindOfClass:[UINavigationController class]]) {
        
            navigation = rootViewController;
        }
    
        return navigation;
    }
    

    4、跳转到升级页面,并杀掉进程

    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"https://itunes.apple.com/cn/app/id1288408888?mt=8"]];
    abort();
    

    5、获取资源目录和document目录

    /*说明:资源文件目录     */
    NSBundle *bundle = [NSBundle mainBundle];
    NSLog(@"%@",bundle);
    
    /*说明:documents文件目录      */
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSLog(@"%@",paths);
    

    6、播放声音代码

        NSURL *fileURL = [[NSBundle mainBundle] URLForResource:fileName withExtension:nil];
        NSData *encryptedData = [NSData dataWithContentsOfURL:fileURL];
        
        NSError *otherError;
        self.player = [[AVAudioPlayer alloc] initWithData:encryptedData error:&otherError];
        [self.player prepareToPlay];
        self.player.delegate = self;
        
        //静音情况下播放
        AVAudioSession *audioSession = [AVAudioSession sharedInstance];
        [audioSession setCategory:AVAudioSessionCategoryPlayback error:nil];
        [audioSession setActive:YES error:nil];
        
        [self.player play];
    

    7、图片压缩

    /**
     图片压缩
    
     @param image 图片
     @param kb 压缩到多少K
     @return 图片数据
     */
    + (NSData *)scaleImage:(UIImage *)image toKb:(NSInteger)kb {
    
        if (!image) {
        
            return nil;
        }
    
        if (kb < 1) {
        
            return nil;
        }
    
        kb *= 1024;
    
        CGFloat compression = 0.9f;
        CGFloat maxCompression = 0.1f;
        NSData *imageData = UIImageJPEGRepresentation(image, compression);
    
        while ([imageData length] > kb && compression > maxCompression) {
        
            compression -= 0.1;
            imageData = UIImageJPEGRepresentation(image, compression);
        }
    
    #ifdef DEBUG
        NSLog(@"Current picture file size: %f kb",(float)[imageData length]/1024.0f);
    #endif
    
        return imageData;
    }
    

    8、几个常用的xcode快捷键

    1、control + command + 上/下       切换.m和.h
    2、control + command + 左/右       上一个文件和下一个文件
    3、shift + command + j            快速定位
    4、shift + command + o            查找文件
    

    相关文章

      网友评论

        本文标题:iOS开发小知识备忘录

        本文链接:https://www.haomeiwen.com/subject/syiyeftx.html