iOS 开发Tips

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

本地JSON文件解析

import UIKit
class YHTag: NSObject {
    var text: String = ""
    var imageurl: String = ""
    
    init(_ text: String, _ imageurl: String) {
        self.text = text
        self.imageurl = imageurl
    }
    class func getToolTag() -> Array<YHTag>? {
        let jsonPath = Bundle.main.path(forResource: "all", ofType: "json")
        let jsonURL = URL(fileURLWithPath: jsonPath!)
        do {
            let jsonData = try Data(contentsOf: jsonURL)
            let jsonDic = try JSONSerialization.jsonObject(with: jsonData, options: JSONSerialization.ReadingOptions.mutableContainers) as? Dictionary<String, Any>
            let result: Dictionary<String, Array<Any>> = (jsonDic!["result"] as? Dictionary<String, Array<Any>>)!
            let tagArray: Array<Dictionary<String, String>> = result["toolTag"] as! Array<Dictionary<String, String>>
            var tagData:Array<YHTag> = []
            for item in tagArray {
                let text = item["text"] ?? "-"
                let imageurl = item["imageurl"] ?? "-"
                let model = YHTag(text, imageurl)
                tagData.append(model)
            }
            return tagData
        } catch {
            debugPrint("=====error: \(error).")
            return nil
        }
    }
}

cocoapods 全新安装

// import Moya 时报错找不到,别慌别慌!
// Targert -> YHFinancial -> Build Phases -> Link Binary With Libraries -> + -> 添加
  • sudo gem install cocoapods
  • pod setup --verbose
  • 在工程文件同级目录下创建Podfile文件(终端)
cd /Users/tangpeijun/Documents/v201805/swift/YHFinancial
vi Podfile
i
platform :ios, '11.0'
use_frameworks!
target 'YHFinancial' do

# 2018-07-24

pod 'Alamofire', '~> 4.7'
pod 'SwiftyJSON', '~> 4.0'
pod 'Moya', '~> 11.0'
pod 'ReachabilitySwift'
pod 'DGElasticPullToRefresh'
pod 'NVActivityIndicatorView'

end
ESC键
:wq

  • cd /Users/tangpeijun/Documents/v201805/swift/YHFinancial
  • pod install
  • pod update

@discardableResult

没有使用返回值时取消警告

for循环遍历

  • 已知集合遍历
let array = [1, 2, 3]
for (index, value) in array.enumerated() {
  print( "=====\(index), \(value)")
}

/* 打印结果
=====0, 1
=====1, 2
=====2, 3
*/
let array = [1, 2, 3]
array.forEach { (element) in
  if element == 2 {
    return
  }
  print("=====\(element)")
}

/* 打印结果
=====1
=====3
*/
  • 已知范围遍历
for element in 1...3 {
  if element == 2 {
     return
  }
  print("=====\(element)")
}

/* 打印结果
=====1
*/

语法糖

  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
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 194,761评论 5 460
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 81,953评论 2 371
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 141,998评论 0 320
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 52,248评论 1 263
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 61,130评论 4 356
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 46,145评论 1 272
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 36,550评论 3 381
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 35,236评论 0 253
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 39,510评论 1 291
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 34,601评论 2 310
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 36,376评论 1 326
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,247评论 3 313
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 37,613评论 3 299
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 28,911评论 0 17
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,191评论 1 250
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 41,532评论 2 342
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 40,739评论 2 335

推荐阅读更多精彩内容

  • 1.NSTimer //暂停if ([timer isValid]) {[timer setFireDate:[N...
    俊月阅读 1,237评论 0 0
  • UINavgationController 的返回按钮被自定义之后,系统的左滑pop功能就会失效。 解决:在控制器...
    kunkunm阅读 515评论 0 3
  • 这篇文章实时更新iOS开发过程中小小得Tips,没有高深的算法和程序架构,设计。就是一个备忘录![最近发现倒序比较...
    HenryPeng阅读 554评论 0 0
  • 天灰的时候,你给我发来两段从荔枝FM上分享过来的故事,说让我没事可以听听。当时我漫不经心风轻云淡地说好,满...
    一玖酒八阅读 877评论 0 2
  • 热爱写作的小伙伴们,是否曾经有过这样的写作经历: 你的脑海里有个非常好的想法,努力写出来以后,发现似乎并不是你当初...
    余老诗写作课阅读 1,648评论 6 26