美文网首页
iOS开发常用技能

iOS开发常用技能

作者: L泽 | 来源:发表于2016-11-04 16:16 被阅读56次

    我把我觉得很好用的方法技能无私奉献一下吧。欢迎收藏关注。

    1.删除某个view上面的所有视图

    [self.jggView.subviewsmakeObjectsPerformSelector:@selector(removeFromSuperview)];

    2.计算label行间距和字间距

    #define UILABEL_LINE_SPACE6

    #define HEIGHT [ [ UIScreen mainScreen ] bounds ].size.height

    //给UILabel设置行间距和字间距

    -(void)setLabelSpace:(UILabel*)label withValue:(NSString*)str withFont:(UIFont*)font {

    NSMutableParagraphStyle*paraStyle = [[NSMutableParagraphStylealloc]init];

    paraStyle.lineBreakMode=NSLineBreakByCharWrapping;

    paraStyle.alignment=NSTextAlignmentLeft;

    paraStyle.lineSpacing=UILABEL_LINE_SPACE; //设置行间距

    paraStyle.hyphenationFactor=1.0;

    paraStyle.firstLineHeadIndent=0.0;

    paraStyle.paragraphSpacingBefore=0.0;

    paraStyle.headIndent=0;

    paraStyle.tailIndent=0;

    //设置字间距NSKernAttributeName:@1.5f

    NSDictionary*dic =@{NSFontAttributeName:font,NSParagraphStyleAttributeName:paraStyle,NSKernAttributeName:@1.5f

    };

    NSAttributedString*attributeStr = [[NSAttributedStringalloc]initWithString:strattributes:dic];

    label.attributedText= attributeStr;

    }

    //计算UILabel的高度(带有行间距的情况)

    -(CGFloat)getSpaceLabelHeight:(NSString*)str withFont:(UIFont*)font withWidth:(CGFloat)width {

    NSMutableParagraphStyle*paraStyle = [[NSMutableParagraphStylealloc]init];

    paraStyle.lineBreakMode=NSLineBreakByCharWrapping;

    paraStyle.alignment=NSTextAlignmentLeft;

    paraStyle.lineSpacing=UILABEL_LINE_SPACE;

    paraStyle.hyphenationFactor=1.0;

    paraStyle.firstLineHeadIndent=0.0;

    paraStyle.paragraphSpacingBefore=0.0;

    paraStyle.headIndent=0;

    paraStyle.tailIndent=0;

    NSDictionary*dic =@{NSFontAttributeName:font,NSParagraphStyleAttributeName:paraStyle,NSKernAttributeName:@1.5f

    };

    CGSizesize = [strboundingRectWithSize:CGSizeMake(width,HEIGHT)options:NSStringDrawingUsesLineFragmentOriginattributes:diccontext:nil].size;

    returnsize.height;

    }

    3.更新约束问题的动态计算cell的高度

    - (CGFloat)tableView:(UITableView*)tableView heightForRowAtIndexPath:(NSIndexPath*)indexPath

    {

    TCell*cell= [TCellshareInstance];

    [cellsetNeedsUpdateConstraints];

    [cellupdateConstraintsIfNeeded];

    [cellsetCellContent:self.data[indexPath.row]];

    [cellsetNeedsLayout];

    [celllayoutIfNeeded];

    CGFloatheight = [cell.contentViewsystemLayoutSizeFittingSize:UILayoutFittingCompressedSize].height;

    returnheight;

    }

    4.定义此两个宏可以有效的使用masonry

    #define MAS_SHORTHAND

    #define MAS_SHORTHAND_GLOBALS

    5.第三方类库(有机会下载几个研究一下也是不错的)

    http://www.th7.cn/Program/IOS/201601/757661.shtml

    6.动画详细介绍

    http://mp.weixin.qq.com/s?__biz=MzIwOTQ3NzU0Mw==&mid=2247483734&idx=1&sn=33a17000f8fba3db79d8e94046915d09#rd

    7.textView添加监听字数

    if ((textView.text.length - range.length + text.length) > MAX_INPUT_LENGTH)

    {

    NSString *substring = [text substringToIndex:MAX_INPUT_LENGTH - (textView.text.length - range.length)];

    NSMutableString *lastString = [textView.text mutableCopy];

    [lastString replaceCharactersInRange:range withString:substring];

    textView.text = [lastString copy];

    return NO;

    }

    else

    {

    return YES;

    }

    8.React-Native框架学习资料

    React-Native学习指南

    本指南汇集React-Native各类学习资源,给大家提供便利。指南正在不断的更新,大家有好的资源欢迎Pull Requests!

    同时还有Awesome React-Native系列

    https://github.com/jondot/awesome-react-native

    教程

    react-native 官方api文档http://facebook.github.io/react-native/docs/getting-started.html

    react-native 中文api文档 (翻译中)https://github.com/ecomfe/react-native-cn

    react.js中文文档http://reactjs.cn/

    react.js入门教程(gitbook)http://hulufei.gitbooks.io/react-tutorial/content/introduction.html

    react.js快速入门教程 - 阮一峰http://www.ruanyifeng.com/blog/2015/03/react.html

    react.js视频教程http://react.nodejs-china.org/t/reactjszhong-wen-shi-pin-jiao-cheng-bai-du-wang-pan/584

    react-native第一课http://html-js.com/article/2783

    深入浅出 React Native:使用 JavaScript 构建原生应用http://zhuanlan.zhihu.com/FrontendMagazine/19996445

    React Native通信机制详解http://blog.cnbang.net/tech/2698/

    React Native布局篇http://segmentfault.com/a/1190000002658374

    React Native 基础练习指北(一)http://segmentfault.com/a/1190000002645929

    React Native 基础练习指北(二)http://segmentfault.com/a/1190000002647733

    构建一个简单的列表页和2页导航http://www.xn--cnq920ntha.cn/archives/235#6838470-tsina-1-17436-6a377b1a66595f9ede646cf5c012734c

    Diary of Building an iOS App with React Nativehttp://herman.asia/building-a-flashcard-app-with-react-native

    Use React Native in Existing iOS Apphttp://blog-en.leapoahead.com/post/use-react-native-in-existing-ios-app

    tcomb-form-native使用视频教程(需翻墙)http://react.rocks/example/tcomb-form-native

    开源APP

    研究源码也是一个很好的学习方式

    官方演示Apphttps://github.com/facebook/react-native/tree/master/Examples

    ReactNativeRubyChinahttps://github.com/henter/ReactNativeRubyChina

    HackerNews-React-Nativehttps://github.com/iSimar/HackerNews-React-Native

    React-Native新闻客户端https://github.com/tabalt/ReactNativeNews

    newswatch(新闻客户端)https://github.com/bradoyler/newswatch-react-native

    buyscreen(购买页面)https://github.com/appintheair/react-native-buyscreen

    V2EX客户端https://github.com/samuel1112/v2er

    react-native-todohttps://github.com/joemaddalone/react-native-todo

    react-native-beerhttps://github.com/muratsu/react-native-beer

    react-native-starshttps://github.com/86/react-native-stars

    模仿天猫首页的apphttps://github.com/baofen14787/react-native-demo

    ReactNativeChesshttps://github.com/csarsam/ReactNativeChess

    react native 编写的音乐软件https://github.com/Johnqing/miumiu

    react-native-pokedexhttps://github.com/ababol/react-native-pokedex

    CNode-React-Nativehttps://github.com/SFantasy/CNode-React-Native

    8tracks电台客户端https://github.com/voronianski/EightTracksReactNative

    React-Native实现的计算器https://github.com/yoxisem544/Calculator-using-React-Native

    房产搜索apphttps://github.com/jawee/react-native-PropertyFinder

    知乎专栏apphttps://github.com/LeezQ/react-native-zhihu-app

    ForeignExchangeApphttps://github.com/peralmq/ForeignExchangeApp

    工具

    react-native-snippets(代码提示)https://github.com/Shrugs/react-native-snippets

    react-native-babel(使用ES6+)https://github.com/roman01la/react-native-babel

    资源网站

    React-native官网http://facebook.github.io/react-native/

    React-China社区http://react-china.org/

    React-native组件库(比较全的组件库)http://react.parts/

    React Native Moduleshttp://reactnativemodules.com/

    11款React Native开源移动 UI 组件http://www.oschina.net/news/61214/11-react-native-ui-components

    业界讨论

    谈谈 React Native - 唐巧http://blog.devtang.com/blog/2015/02/01/talk-about-react-native/

    如何评价React-Native?http://www.zhihu.com/question/27852694/answer/43990708

    React Native概述:背景、规划和风险http://div.io/topic/938

    指南:https://github.com/ele828/react-native-guide

    9.cocopods文件添加到整个工程以及一些可用的注意事项

    1.使用CocoaPods导入头文件不能提示?

    在BuildSettings中搜索Header Search Path,然后设置$(PODS_ROOT),并勾选recursive支持递归搜索。

    2.代码片段路径:~/Library/Developer/Xcode/UserData/CodeSnippets

    1.Too many arguments to function call, expected 0, have 2

    - Project - Build Settings - ENABLE_STRICT_OBJC_MSGSEND将其设置为NO

    2.导入pch文件

    (1)Building Setting中搜索pref

    (2)将Prefix Header的值设为$(SRCROOT)/$(PRODUCT_NAME)/$(PRODUCT_NAME).pch

    3.sizeClass经验总结:

    (1)所有公用的控件要出现在**

    (2)所有公共的约束需要出现在**

    (2)所有的大块view,如果内部子控件的约束是固定的,约束需要写在**中。

    总结:在**中要指定大小,同时一般不指定位置,你可以手动拖动位置,便于查看,在其他详细界面再正确调整,这样多个sizeclass查看界面就不会显得很乱。

    10.离线缓存

    基于NSURLSession+NSURLProtol的UIWebView离线缓存 主要是使用苹果的黑魔法类:NSURLProtocol来对网络请求进行拦截,拦截后使用自定义的网络去加载数据后进行离线缓存。这样保证在没有网络的情况下,也能保证离线能对之前webView进行浏览

    11.button 添加双击事件 并且取消单击事件

    单击事件:

    -(void)singleClick:(UIButton *)button forEvent:(UIEvent *)event{

    [self performSelector:@selector(tabButtonTap:) withObject:button afterDelay:0.2];

    }

    - (void)tabButtonTap:(UIButton *)sender {

    NSLog(@"单击操作");

    }

    双击事件:

    -(void)doubleClick:(UIButton *)button forEvent:(UIEvent *)event

    {

    [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(tabButtonTap:) object:button];

    NSLog(@"双击操作");

    }

    这个方法

    [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(tabButtonTap:) object:button];

    解释是Cancels perform requests previously registered with performSelector:withObject:afterDelay:

    就是把performSelector:withObject:afterDelay:以前注册的请求取消掉,从代码上看就是取消了tabButtonTap:方法。

    但是只能在一个运行循环范围内有效。所以通过这样子就把单击的事件取消了,在后面就可以实现双击的操作,而不必担心会先触发单击。

    12.定制tableView的分割线

    - (void)tableView:(UITableView*)tableView willDisplayCell:(UITableViewCell*)cell forRowAtIndexPath:(NSIndexPath*)indexPath

    {

    UIEdgeInsetsinsets =UIEdgeInsetsMake(10,10,10,30);

    //三个方法并用,实现自定义分割线效果

    if([cellrespondsToSelector:@selector(setSeparatorInset:)]) {

    cell.separatorInset= insets;

    }

    if([cellrespondsToSelector:@selector(setLayoutMargins:)]) {

    [cellsetLayoutMargins:insets];

    }

    if([cellrespondsToSelector:@selector(setPreservesSuperviewLayoutMargins:)]){

    [cellsetPreservesSuperviewLayoutMargins:NO];

    }

    }

    实现如下:

    UITableView中将分割线样式改为None

    tableView.separatorStyle = UITableViewCellSeparatorStyleNone;

    自定义UITableViewCell中复写- (void)drawRect:(CGRect)rect方法

    - (void)drawRect:(CGRect)rect { CGContextRef context = UIGraphicsGetCurrentContext(); CGContextSetFillColorWithColor(context, [UIColor clearColor].CGColor); CGContextFillRect(context, rect); //上分割线, CGContextSetStrokeColorWithColor(context, [UIColor colorWithHexString:@"ffffff"].CGColor); CGContextStrokeRect(context, CGRectMake(5, -1, rect.size.width - 10, 1)); //下分割线 CGContextSetStrokeColorWithColor(context, [UIColor colorWithHexString:@"e2e2e2"].CGColor); CGContextStrokeRect(context, CGRectMake(5, rect.size.height, rect.size.width - 10, 1)); }

    13.保存网络加载的启动图片。

    NSDictionary*responseDic = (NSDictionary*)responseObject;

    NSDictionary*dic = [responseDicobjectForKey:@"data"];

    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT,0), ^{

    if(dic) {

    NSString*picUrl = [dicobjectForKey:@"pic_url"];

    if([picUrlisEqualToString:@""]) {

    NSLog(@"pic_url:%@",picUrl);

    }else{

    NSData*data = [NSDatadataWithContentsOfURL:[NSURLURLWithString:picUrl]];

    UIImage*image = [UIImageimageWithData:data];

    NSArray*paths =NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES);

    NSString*filePath = [[pathsobjectAtIndex:0]stringByAppendingPathComponent:[NSStringstringWithFormat:@"loading.png"]];//保存文件的名称

    //    BOOL result = [UIImagePNGRepresentation() writeToFile: filePath    atomically:YES]; //保存成功会返回YES

    NSLog(@"paths:%@    %@",paths,filePath);

    [UIImagePNGRepresentation(image)writeToFile:filePathatomically:YES];

    }

    }

    });

    }failure:^(NSError*error) {

    NSLog(@"加载启动页广告失败");

    }];

    14.常量

    常量是容易重复被使用和无需通过查找和代替就能快速修改值。常量应该使用static来声明而不是使用#define,除非显式地使用宏。

    应该:

    [cpp] view plaincopy

    1 static NSString * const RWTAboutViewControllerCompanyName = @"RayWenderlich.com";

    2 static CGFloat const RWTImageThumbnailHeight = 50.0;

    不应该:

    [cpp] view plaincopy

    1 #define CompanyName @"RayWenderlich.com"

    2 #define thumbnailHeight 2

    15.UITextField 限制输入数字

    限制只能输入特定的字符

    (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{

    NSCharacterSet *cs;

    cs = [[NSCharacterSet characterSetWithCharactersInString:NUMBERS]invertedSet];

    NSString *filtered = [[string componentsSeparatedByCharactersInSet:cs]componentsJoinedByString:@""]; //按cs分离出数组,数组按@""分离出字符串

    BOOL canChange = [string isEqualToString:filtered];

    return canChange;

    }

    上面那个NUMBERS是一个宏,可以在文件顶部定义:

    #define NUMBERS @”0123456789\\n” (这个代表可以输入数字和换行,请注意这个\\n,如果不写这个,Done按键将不会触发,如果用在SearchBar中,将会不触发Search事件,因为你自己限制不让输入\\n,好惨,我在项目中才发现的。)

    所以,如果你要限制输入英文和数字的话,就可以把这个定义为:

    #define kAlphaNum   @”ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789″。

    当然,你还可以在以上方法return之前,做一提示的,比如提示用户只能输入数字之类的。如果你觉得有需要的话。

    限制只能输入一定长度的字符

    - (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string;

    {  //string就是此时输入的那个字符 textField就是此时正在输入的那个输入框 返回YES就是可以改变输入框的值 NO相反

    if ([string isEqualToString:@"\\n"])  //按会车可以改变

    {

    return YES;

    }

    NSString * toBeString = [textField.text stringByReplacingCharactersInRange:range withString:string]; //得到输入框的内容

    if (self.myTextField == textField)  //判断是否时我们想要限定的那个输入框

    {

    if ([toBeString length] > 20) { //如果输入框内容大于20则弹出警告

    textField.text = [toBeString substringToIndex:20];

    UIAlertView *alert = [[[UIAlertView alloc] initWithTitle:nil message:@"超过最大字数不能输入了" delegate:nil cancelButtonTitle:@"Ok" otherButtonTitles:nil, nil] autorelease];

    [alert show];

    return NO;

    }

    }

    return YES;

    }

    16.当用masonry做约束 需要获取约束之后的具体的frame值你需要这么做。

    调用layoutIfNeeded。

    期待接下来的更新吧 小伙子。

    相关文章

      网友评论

          本文标题:iOS开发常用技能

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