iOS 开发Tips

作者: 印林泉 | 来源:发表于2017-08-30 19:15 被阅读53次

    iOS 两行终端命令计算代码量

    cd /Users/yinlinqvan/iOS/我的企业级项目/201703善林金 融/亿宝贷借款/xjd_llzf/SLCashLoan/SLCashLoan
    
    find . "(" -name "*.m" -or -name "*.mm" -or -name "*.cpp" -or -name "*.h" -or -name "*.rss" ")" -print | xargs wc -l
    

    语法糖

    1. 字面量语法
      @1
      @[@"1", @"2"]
      @{@"key": @"value"}
      (CGRect){0, 0, 100, 100}
      (CGPoint){100, 100}
    2. 可视化格式语言vfl
    /**
     设置活动指示器约束
     */
    - (void)setupActivityIndicatorView {
        _activityIndicatorView = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];
        [_activityIndicatorView setColor:kActivityIndicatorViewColor];
        [_activityIndicatorView setHidesWhenStopped:YES];
        [self.view addSubview:_activityIndicatorView];
        
        [_activityIndicatorView setTranslatesAutoresizingMaskIntoConstraints:NO];
        NSDictionary *views = @{@"activityIndicatorView": _activityIndicatorView};
        NSString *visualFormatLanguage = @"|-[activityIndicatorView]-|";//可视化格式语言vfl
        NSArray *contraintsX = [NSLayoutConstraint constraintsWithVisualFormat:visualFormatLanguage options:NSLayoutFormatAlignAllCenterX metrics:nil views:views];
        [self.view addConstraints:contraintsX];
        
        NSArray *contraintsY = [NSLayoutConstraint constraintsWithVisualFormat:@"V:|-[activityIndicatorView]-|" options:NSLayoutFormatAlignAllCenterY metrics:nil views:views];
        [self.view addConstraints:contraintsY];
    }
    

    悬停按钮

    固定约束

    UITextField

    textfield.text可能是空字符串,也可能是nil

    iOS Reavel

    • 对所有出现的崩溃的数据都要进行判空处理,要负责任
    • 查找常量重复(const修饰)

    连接文件服务器

    • 打开finder > 前往(快捷键:command + K)
    • 服务器地址:smb://192.168.188.19

    键盘高度

    - (void)keyboardWillShow:(NSNotification *)aNotification {
        //呼出键盘
        NSDictionary *userInfo = [aNotification userInfo];
        NSValue *aValue = [userInfo objectForKey:UIKeyboardFrameEndUserInfoKey];
        CGRect keyboardRect = [aValue CGRectValue];
        _keyboardH = keyboardRect.size.height;
    }
    

    打印日志

    #ifdef DEBUG  
    #define NSLog(...) NSLog(__VA_ARGS__)  
    #define debugMethod() NSLog(@"%s", __func__)  
    #else  
    #define NSLog(...)  
    #define debugMethod()  
    #endif  
    

    Universal Links通用链接

    http://www.jianshu.com/p/693459b618e5

    格式化%zd 解决整型警告

    respondsToSelector:

    https://segmentfault.com/q/1010000004682116

    钥匙串

    colorset

    PDFKit

    .archive

    比如国家、省份、城市、区县、街道直接归档,解决卡顿

    代码方式调整屏幕亮度

    // brightness属性值在0-1之间,0代表最小亮度,1代表最大亮度
    [[UIScreen mainScreen] setBrightness:0.5];
    

    通知监听APP生命周期

    1. UIApplicationDidEnterBackgroundNotification 应用程序进入后台
    2. UIApplicationWillEnterForegroundNotification 应用程序将要进入前台
    3. UIApplicationDidFinishLaunchingNotification 应用程序完成启动
    4. UIApplicationDidFinishLaunchingNotification 应用程序由挂起变的活跃
    5. UIApplicationWillResignActiveNotification 应用程序挂起(有电话进来或者锁屏)
    6. UIApplicationDidReceiveMemoryWarningNotification 应用程序收到内存警告
    7. UIApplicationDidReceiveMemoryWarningNotification 应用程序终止(后台杀死、手机关机等)
    8. UIApplicationSignificantTimeChangeNotification 当有重大时间改变(凌晨0点,设备时间被修改,时区改变等)
    9. UIApplicationWillChangeStatusBarOrientationNotification 设备方向将要改变
    10. UIApplicationDidChangeStatusBarOrientationNotification 设备方向改变
    11. UIApplicationWillChangeStatusBarFrameNotification 设备状态栏frame将要改变
    12. UIApplicationDidChangeStatusBarFrameNotification 设备状态栏frame改变
    13. UIApplicationBackgroundRefreshStatusDidChangeNotification 应用程序在后台下载内容的状态发生变化
    14. UIApplicationProtectedDataWillBecomeUnavailable 本地受保护的文件被锁定,无法访问
    15. UIApplicationProtectedDataWillBecomeUnavailable 本地受保护的文件可用了

    常用Git操作

    1. 切换用户
    2. 新建分支
    3. 切换分支
    4. 关联远程仓库

    iOS App Store 审核被拒

    1、禁用版本更新按钮
    2、隐私权限详细说明
    3、隐私权限使用入口
    4、后台获取隐私权限必要性说明必须在备注中说明
    5、看门狗wactchdog崩溃,AppDelegate删掉同步请求,或改用异步请求版本信息
    https://developer.apple.com/library/content/qa/qa1693/_index.html

    当UITextView/UITextField中没有文字时,禁用回车键

    textField.enablesReturnKeyAutomatically = YES;
    

    从导航控制器中删除某个控制器

    NSMutableArray *navigationArray = [[NSMutableArray alloc] initWithArray: self.navigationController.viewControllers];
    [navigationArray removeObjectAtIndex: 2]; 
    self.navigationController.viewControllers = navigationArray;
    

    将一个view保存为pdf格式

    - (void)createPDFfromUIView:(UIView*)aView saveToDocumentsWithFileName:(NSString*)aFilename {
        NSMutableData *pdfData = [NSMutableData data];
        UIGraphicsBeginPDFContextToData(pdfData, aView.bounds, nil);
        UIGraphicsBeginPDFPage();
        CGContextRef pdfContext = UIGraphicsGetCurrentContext();
        [aView.layer renderInContext:pdfContext];
        UIGraphicsEndPDFContext();
    
        NSArray* documentDirectories = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask,YES);
        NSString* documentDirectory = [documentDirectories objectAtIndex:0];
        NSString* documentDirectoryFilename = [documentDirectory stringByAppendingPathComponent:aFilename];
        [pdfData writeToFile:documentDirectoryFilename atomically:YES];
        NSLog(@"documentDirectoryFileName: %@",documentDirectoryFilename);
    }
    

    判断两个区域是否有重合

    if (CGRectIntersectsRect(rect1, rect2)) {
    }
    

    查看系统所有字体

    for (id familyName in [UIFont familyNames]) {
        NSLog(@"%@", familyName);
        for (id fontName in [UIFont fontNamesForFamilyName:familyName]) NSLog(@"  %@", fontName);
    }
    

    添加.pch文件

    1. 创建新文件 ios->other->PCH file,创建一个pch文件:“工程名-Prefix.pch”
    2. 将building setting中的precompile header选项的路径添加“$(SRCROOT)/项目名称/pch文件名”(例如:$(SRCROOT)/项目名称/工程名-Prefix.pch)
    3. 将Precompile Prefix Header为YES,预编译后的pch文件会被缓存起来,可以提高编译速度

    私有API(不能用)

    1. 点击Home键的效果(程序挂起):[[UIApplication sharedApplication] performSelector:@selector(suspend)];

    UIWebView高度

    - (void)webViewDidFinishLoad:(UIWebView *)webView {
        CGFloat height = [[webView stringByEvaluatingJavaScriptFromString:@"document.body.offsetHeight"] floatValue];      CGRect frame = webView.frame;
        webView.frame = CGRectMake(frame.origin.x, frame.origin.y, frame.size.width, height);
    }
    

    数据库操作:增、删、改、查

    1. 增:insert into tb_blogs(name, url) values('aaa','http://www.baidu.com');
    2. 删:delete from tb_blogs where blogid = 1;
    3. 改:update tb_blogs set url = 'www.baidu.com' where blogid = 1;
    4. 查:select name, url from tb_blogs where blogid = 1;
    5. 联表查询

    数组逆序遍历

    NSArray *array = @[@"1",@"2",@"3",@"5",@"6"];
    [array enumerateObjectsWithOptions:NSEnumerationReverse usingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
    NSLog(@"%@",obj);
    }];
    

    数组遍历

    [self.navigationController.childViewControllers enumerateObjectsUsingBlock:^(__kindof UIViewController * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        if ([obj isKindOfClass:NSClassFromString(@"SLCashLoanViewController")] || [obj isKindOfClass:NSClassFromString(@"SLCreditLoanViewController")] || [obj isKindOfClass:NSClassFromString(@"SLAccountViewController")]) {
            [self.navigationController popToViewController:obj animated:YES];
            *stop = YES;
        }
    }];
    

    禁用复制粘贴菜单

    - (BOOL)canPerformAction:(SEL)action withSender:(id)sender {
        if ([UIMenuController sharedMenuController]) {
            [UIMenuController sharedMenuController].menuVisible = NO;
        }
        return NO;
    }
    

    设置展位文本字体颜色大小

    UITextField *textField = [[UITextField alloc] initWithFrame:(CGRect){0, 0, 200, 44}];
    textField.placeholder = @"请输入用户名";
    [textField setValue:[UIColor redColor] forKeyPath:@"_placeholderLabel.textColor"];
    [textField setValue:[UIFont boldSystemFontOfSize:16] forKeyPath:@"_placeholderLabel.font"];
    

    富文本库

    设置状态栏样式

    - (UIStatusBarStyle)preferredStatusBarStyle {
        return  UIStatusBarStyleLightContent;
    }
    

    edgesForExtendedLayout

    因为一般为了不让tableView 不延伸到 navigationBar 下面, 属性设置为 UIRectEdgeNone。这时会发现导航栏变灰了,处理如下就OK了
    self.navigationController.navigationBar.translucent = NO;

    automaticallyAdjustsScrollViewInsetsNO时,tableview 是从屏幕的最上边开始,也就是被导航栏、状态栏覆盖。
    automaticallyAdjustsScrollViewInsetsYES时,tableView 上下滑动时,是可以穿过导航栏、状态栏的,在他们下面有淡淡的浅浅红色。

    extendedLayoutIncludesOpaqueBars首先看下官方解释,默认 NO, 但是Bar 的默认属性是 透明的。也就是说只有在不透明下才有用但是,测试结果很软肋,基本区别不大。但是对于解决一些Bug 是还是起作用的,比如说SearchBar的跳动问题。

    iOS 设置状态栏

    设置导航栏在滑动时高度约束改为20,则状态栏就可以显示导航栏的图片部分

    iOS UITabBarController切换选项卡,关闭模态视图回到主视图

    从任意页面,切换选项卡
    关闭模态视图回到主视图

    //跳转并切换选项卡
    dispatch_async(dispatch_get_main_queue(), ^{
        [self.navigationController popToRootViewControllerAnimated:NO];
        SLTabBarController *tabC = (SLTabBarController *)[UIApplication sharedApplication].keyWindow.rootViewController;
        tabC.selectedIndex= 1;
    });
    

    iOS 获取UIWebView的高度

    /**
     获取UIWebView的高度
    
     @param webView UIWebView
     */
    - (void)webViewDidFinishLoad:(UIWebView *)webView  {
        CGFloat height = [[webView stringByEvaluatingJavaScriptFromString:@"document.body.offsetHeight"] floatValue];
        CGRect frame = webView.frame;
        webView.frame = CGRectMake(frame.origin.x, frame.origin.y, frame.size.width, height);
    }
    

    iOS UUID(AdSupport )

    + (NSString *)getUUIDString {
        CFUUIDRef uuidRef = CFUUIDCreate(kCFAllocatorDefault);
        CFStringRef strRef = CFUUIDCreateString(kCFAllocatorDefault , uuidRef);
        NSString *uuidString = (__bridge NSString*)strRef;
        CFRelease(strRef);
        CFRelease(uuidRef);
        [SLFileCacheManager saveUserData:uuidString forKey:@"uuid"];
        return uuidString;
    }
    

    iOS 获取设备名称

    [[UIDevice currentDevice] name]
    

    iOS ADID

    [[[ASIdentifierManager sharedManager] advertisingIdentifier] UUIDString]]
    

    iOS 数据精度

    - (void)useNSDecimalNumber {
        int unit = 10000;//万
        CGFloat money = 10000000.1;
        NSDecimalNumber *moneyDecimalNumber = [[NSDecimalNumber alloc] initWithFloat:money];
        CGFloat f = [NSString stringWithFormat:@"%.2f", money/unit].floatValue;//10.00万
        NSDecimalNumber *dn = [[NSDecimalNumber alloc] initWithFloat:f];
        NSLog(@"===%@是%@万", moneyDecimalNumber, dn);
    }
    

    iOS 评分

     [[UIApplicationsharedApplication]openURL:[NSURLURLWithString:@"http://itunes.apple.com/WebObjects/MZStore.woa/wa/viewContentsUserReviews?id=APPID&pageNumber=0&sortOrdering=2&type=Purple+Software&mt=8"]];
    

    懒加载与重写setter、getter方法

    • 懒加载
    - (NSArray *)data {
        if (!_data) {
            _data = [NSArray arrayWithContentsOfFile:
    [[NSBundle mainBundle] pathForResource:@"data" ofType:@"plist"]];
        }
        return _data;
    }
    

    自动生成技术文档headerdoc

    # shell script goes here
    mkdir ~/Desktop/SLHeaderdoc/Class
    find /Users/shanlin/Desktop/现金贷/xjd/SLCashLoan/SLCashLoan/Class/ -name \*.h -print | xargs headerdoc2html -o ~/Desktop/SLHeaderdoc/
    gatherheaderdoc ~/Desktop/SLHeaderdoc/ index.html
    exit 0
    
    headerdoc.jpg

    相关文章

      网友评论

        本文标题:iOS 开发Tips

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