IOS 开发过程中问题汇总

IOS 开发过程中问题汇总 1-调用打电话方法 1> 直接跳转到打电话页面 __拨打完电话回不到原来的应用,会停留在通讯录里,而且是直接拨打,不弹出提示

[[UIApplication sharedApplication] openURL:[NSURL URLWithString:[NSString stringWithFormat:@“tel://%@",@"4001588168"]]];

【IOS 开发过程中问题汇总】2> 自动弹出提示选择后跳转到打电话页面 _ 会回去到原来的程序里(注意这里的telprompt),也会弹出提示 (可能会被拒)
NSString *telNumber = [NSString stringWithFormat:@"telprompt://%@",self.telePhoneNum];

3>这种方法,打完电话后还会回到原来的程序,也会弹出提示,推荐这种
NSMutableString * str=[[NSMutableString alloc] initWithFormat:@"tel:%@",@"186xxxx6979"]; UIWebView * callWebview = [[UIWebView alloc] init]; [callWebview loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:str]]];

2、UIButton 按钮上得字左对齐 titleEdgeInsets应该是最好的方法,如果只是简单的左对齐,也可以如下方法。
btn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;

3、把字符串中的图片地址转换到数组中
- (NSArray*)getImgArrFromImgStr:(NSString*)imgStr { return [imgStr componentsSeparatedByString:@","]; }

4、把视图添加到键盘上
for(UIView *window in [UIApplication sharedApplication].windows) { if ([window isKindOfClass:NSClassFromString(@“UIRemoteKeyboardWindow")]) { [window addSubview:_doneInKeyboardButton]; } }- (void)registerForKeyboardNotifications { [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWasShown:) name:UIKeyboardWillShowNotification object:nil]; [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWasHidden:) name:UIKeyboardWillHideNotification object:nil]; } - (void) keyboardWasShown:(NSNotification *) notification{ // NSNotification中的 userInfo字典中包含键盘的位置和大小等信息 NSDictionary *userInfo = [notification userInfo]; // UIKeyboardAnimationDurationUserInfoKey 对应键盘弹出的动画时间 CGFloat animationDuration = [[userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey] floatValue]; // UIKeyboardAnimationCurveUserInfoKey 对应键盘弹出的动画类型 NSInteger animationCurve = [[userInfo objectForKey:UIKeyboardAnimationCurveUserInfoKey] integerValue]; //数字彩,数字键盘添加“完成”按钮 if (_doneInKeyboardButton){[UIView beginAnimations:nil context:NULL]; [UIView setAnimationDuration:animationDuration]; //设置添加按钮的动画时间 [UIView setAnimationCurve:(UIViewAnimationCurve)animationCurve]; //设置添加按钮的动画类型//设置自定制按钮的添加位置(这里为数字键盘添加“完成”按钮) _doneInKeyboardButton.transform=CGAffineTransformTranslate(_doneInKeyboardButton.transform, 0, -53); [UIView commitAnimations]; } }- (void) keyboardWasHidden:(NSNotification *)notification { // NSNotification中的 userInfo字典中包含键盘的位置和大小等信息 NSDictionary *userInfo = [notification userInfo]; // UIKeyboardAnimationDurationUserInfoKey 对应键盘收起的动画时间 CGFloat animationDuration = [[userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey] floatValue]/3; if (_doneInKeyboardButton.superview) { [UIView animateWithDuration:animationDuration animations:^{ //动画内容,将自定制按钮移回初始位置 _doneInKeyboardButton.transform=CGAffineTransformIdentity; } completion:^(BOOL finished) { //动画结束后移除自定制的按钮 [_doneInKeyboardButton removeFromSuperview]; }]; } } - (void)configDoneInKeyBoardButton { CGFloat screenHeight = [UIScreen mainScreen].bounds.size.height; //初始化 if (_doneInKeyboardButton == nil) { UIButton *doneInKeyboardButton = [UIButton buttonWithType:UIButtonTypeCustom]; [doneInKeyboardButton setTitle:@"·" forState:UIControlStateNormal]; [doneInKeyboardButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal]; doneInKeyboardButton.backgroundColor = [UIColor clearColor]; doneInKeyboardButton.frame = CGRectMake(0, screenHeight, (KScreenW - 2)/3, 53); doneInKeyboardButton.titleLabel.font = [UIFont systemFontOfSize:35]; doneInKeyboardButton.adjustsImageWhenHighlighted = NO; [doneInKeyboardButton addTarget:self action:@selector(finishAction) forControlEvents:UIControlEventTouchUpInside]; _doneInKeyboardButton = doneInKeyboardButton; } //每次必须从新设定“小数点”按钮的初始化坐标位置 _doneInKeyboardButton.frame = CGRectMake(0, screenHeight, (KScreenW - 2)/3, 53); //由于ios8下,键盘所在的window视图还没有初始化完成,调用在下一次 runloop 下获得键盘所在的window视图 [self performSelector:@selector(addDoneButton) withObject:nil afterDelay:0.0f]; } #pragma mark - 添加小数点按钮 - (void)addDoneButton{ //获得键盘所在的window视图,直接加到window上 for(UIView *window in [UIApplication sharedApplication].windows) { if([window isKindOfClass:NSClassFromString(@"UIRemoteKeyboardWindow")]) { [window addSubview:_doneInKeyboardButton]; } } } #pragma mark - 点击“小数点”按钮事件 -(void)finishAction { _czNumTF.text = [NSString stringWithFormat:@"%@.",_czNumTF.text]; }

5、UILabel的自适应 5.1、UILabel的宽度自适应
adjustsFontSizeToFitWidth

5.2、UILabel的高度自适应
boundingRectWithSize: options:attributes: context: sizeThatFits:

6、UITextField 的 placeholder的颜色改变
//第一种 UIColor *color = [UIColor whiteColor]; _userName.attributedPlaceholder = [[NSAttributedString alloc] initWithString:@"用户名" attributes:@{NSForegroundColorAttributeName: color}]; //第二种 [_userName setValue:[UIColor whiteColor] forKeyPath:@"_placeholderLabel.textColor"];

7、保存图片到相册
- (IBAction)saveImageToAlbum:(id)sender { UIImageWriteToSavedPhotosAlbum(self.imageView.image, self, @selector(imageSavedToPhotosAlbum:didFinishSavingWithError:contextInfo:), nil); } - (void)imageSavedToPhotosAlbum:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo { NSString *message = @"呵呵"; if (!error) { message = @"成功保存到相册"; }else { message = [error description]; } NSLog(@"message is %@",message); }

8、edgesForExtendedLayout edgesForExtendedLayout是一个类型为UIExtendedEdge的属性,指定边缘要延伸的方向。
因为iOS7鼓励全屏布局,它的默认值很自然地是UIRectEdgeAll,四周边缘均延伸,就是说,如果即使视图中上有navigationBar,下有tabBar,那么视图仍会延伸覆盖到四周的区域。
9、 automaticallyAdjustsScrollViewInsets 当 automaticallyAdjustsScrollViewInsets 为 NO 时,tableview 是从屏幕的最上边开始,也就是被 导航栏 & 状态栏覆盖。 当 automaticallyAdjustsScrollViewInsets 为 YES 时,也是默认行为,表现就比较正常了,和edgesForExtendedLayout = UIRectEdgeNone 有啥区别? 不注意可能很难觉察, automaticallyAdjustsScrollViewInsets 为YES 时,tableView 上下滑动时,是可以穿过导航栏&状态栏的,在他们下面有淡淡的浅浅红色
10、extendedLayoutIncludesOpaqueBars 首先看下官方解释,默认 NO, 但是Bar 的默认属性是透明的。。。也就是说只有在不透明下才有用但是,测试结果很软肋,基本区别不大。。。但是对于解决一些Bug 是还是起作用的,比如说SearchBar的跳动问题,详情见:http://www.cnblogs.com/skyming/p/4059128.html, 其他UITableView,UIScrollView 位置的问题多数和这3属性相关。
11、正则表达式的用法
//电话号码 NSString *telPattern = @"\\d{3,4}-)\\d{7,8}$"; //手机号码 NSString *phonePattern = @"^1(3[0-9]|5[0-35-9]|8[025-9])\\d{8}$"; //QQ号码 NSString *QQPattern = @"^[1-9]\\d[4,10]$"; //邮箱地址 NSString *mailPattern = @"^\\w+([-+.]\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*$"; //URL网址 NSString *urlPattern = @"((http[s]{0,1}|ftp)://[a-zA-Z0-9\\.\\-]+\\.([a-zA-Z]{2,4})(:\\d+)?(/[a-zA-Z0-9\\.\\-~!@#$%^&*+?:_/=<>]*)?)|(www.[a-zA-Z0-9\\.\\-]+\\.([a-zA-Z]{2,4})(:\\d+)?(/[a-zA-Z0-9\\.\\-~!@#$%^&*+?:_/=<>]*)?)"; //身份证号码 NSString *IDCardPattern = @"\\d{14}[[0-9],0-9xX]"; //数字和字母 NSString *numCharacterPattern = @"^[A-Za-z0-9]+$"; //整数和小数 NSString *allNumPattern = @"^[0-9]+([.]{0,1}[0-9]+){0,1}$"; //汉字 NSString *hansPattern = @"^[\u4e00-\u9fa5]{0,}$"; //iP地址 NSString *ipPattern = @“((2[0-4]\\d|25[0-5]|[01]?\\d\\d?)\\.){3}(2[0-4]\\d|25[0-5]|[01]?\\d\\d?)"; NSString *pattern = [NSString stringWithFormat:@“%@|%@|%@|%@|%@|%@|%@|%@|%@|%@",telPattern,phonePattern,QQPattern,mailPattern,urlPattern,IDCardPattern,numCharacterPattern,allNumPattern,hansPattern,ipPattern]; NSRegularExpression *reges = [[NSRegularExpression alloc] initWithPattern:pattern options:0 error:nil]; NSString *str = @“————“; NSArray *results = [reges matchesInString:str options:0 range:NSMakeRange(0, str.length)]; for (NSTextCheckingResult *result in results) { NSLog(@"%@ %@",NSStringFromRange(result.range),[str substringWithRange:result.range]); }

12、数组排序
NSArray *array = [NSArray array]; [array sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) { if (obj1 > obj2) { return NSOrderedAscending; //升序 } return NSOrderedDescending; //降序 }];

13、Iphone 各版本的尺寸,分辨率
3.5英寸——Iphone5 :320 x 480640 x 960 4.0英寸——Iphone5s :320 x 568640 x 1136 4.7英寸——Iphone6 :375 x 667750 x 1334 5.5英寸——Iphone6 plus :414 x 7361080 x 1920

14、将项目的.svn全部删除
打开终端,进入项目所在的文件夹:使用命令find . -type d -name ".svn" |xargs rm -rvf就可将项目的.svn全部删除;

15、根据value快速查找数组中的模型(谓词)
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"key = %@",value]; NSArray *array = [modelArray filteredArrayUsingPredicate:predicate];

16、图片的拉伸
image= [image stretchableImageWithLeftCapWidth:image.size.width * 0.5 topCapHeight:image.size.height * 0.5];

17、修改字间距
NSMutableAttributedString *attr = [[NSMutableAttributedString alloc] initWithString:textField.text]; [attr addAttribute:NSKernAttributeName value:[NSNumber numberWithFloat:4.0] range:NSMakeRange(0, textField.text.length)]; textField.attributedText = attr;

18、研究富文本AttributedString
1> NSFontAttributeName设置字体属性,默认值:字体:Helvetica(Neue) 字号:12 2> NSForegroundColorAttributeName设置字体颜色,取值为 UIColor对象,默认值为黑色 3> NSBackgroundColorAttributeName设置字体所在区域背景颜色,取值为 UIColor对象,默认值为nil, 透明色 4> NSLigatureAttributeName设置连体属性,取值为NSNumber 对象(整数),0 表示没有连体字符,1 表示使用默认的连体字符 5> NSKernAttributeName设定字符间距,取值为 NSNumber 对象(整数),正值间距加宽,负值间距变窄 6> NSStrikethroughStyleAttributeName设置删除线,取值为 NSNumber 对象(整数) 7> NSStrikethroughColorAttributeName设置删除线颜色,取值为 UIColor 对象,默认值为黑色——设置中划线 [NSNumber numberWithInteger:NSUnderlineStyleSingle] 8> NSUnderlineStyleAttributeName设置下划线,取值为 NSNumber 对象(整数),枚举常量 NSUnderlineStyle中的值,与删除线类似 9> NSUnderlineColorAttributeName设置下划线颜色,取值为 UIColor 对象,默认值为黑色 10> NSStrokeWidthAttributeName设置笔画宽度,取值为 NSNumber 对象(整数),负值填充效果,正值中空效果 11> NSStrokeColorAttributeName填充部分颜色,不是字体颜色,取值为 UIColor 对象 12> NSShadowAttributeName设置阴影属性,取值为 NSShadow 对象 13> NSTextEffectAttributeName设置文本特殊效果,取值为 NSString 对象,目前只有图版印刷效果可用: 14> NSBaselineOffsetAttributeName设置基线偏移值,取值为 NSNumber (float),正值上偏,负值下偏 15> NSObliquenessAttributeName设置字形倾斜度,取值为 NSNumber (float),正值右倾,负值左倾 16> NSExpansionAttributeName设置文本横向拉伸属性,取值为 NSNumber (float),正值横向拉伸文本,负值横向压缩文本 17> NSWritingDirectionAttributeName设置文字书写方向,从左向右书写或者从右向左书写 18> NSVerticalGlyphFormAttributeName设置文字排版方向,取值为 NSNumber 对象(整数),0 表示横排文本,1 表示竖排文本 19> NSLinkAttributeName设置链接属性,点击后调用浏览器打开指定URL地址 20> NSAttachmentAttributeName设置文本附件,取值为NSTextAttachment对象,常用于文字图片混排 21> NSParagraphStyleAttributeName设置文本段落排版格式,取值为 NSParagraphStyle 对象

19、解决UITableView分割线显示不全,左边有一段缺失
//下面code 可以解决 - (void)viewDidLayoutSubviews { if ([self.tableView respondsToSelector:@selector(setSeparatorInset:)]) { [self.tableView setSeparatorInset:UIEdgeInsetsZero]; } if ([self.tableView respondsToSelector:@selector(setLayoutMargins:)]){ [self.tableView setLayoutMargins:UIEdgeInsetsZero]; } } - (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPat{ if ([cell respondsToSelector:@selector(setLayoutMargins:)]) { [cell setLayoutMargins:UIEdgeInsetsZero]; } if ([cell respondsToSelector:@selector(setSeparatorInset:)]){ [cell setSeparatorInset:UIEdgeInsetsZero]; } }

20、UITableView的row少时没有数据的cell显示分割线的问题
[tableView setTableFooterView:[[UIView alloc] initWithFrame:CGRectZero]];

21、UILabel的文字左右对齐
- (void)conversionCharacterInterval:(NSInteger)maxInteger current:(NSString *)currentString withLabel:(UILabel *)label { CGRect rect = [[currentString substringToIndex:1] boundingRectWithSize:CGSizeMake(200,label.frame.size.height) options:NSStringDrawingUsesLineFragmentOrigin |NSStringDrawingUsesFontLeading attributes:@{NSFontAttributeName: label.font} context:nil]; NSMutableAttributedString *attrString = [[NSMutableAttributedString alloc] initWithString:currentString]; float strLength = [self getLengthOfString:currentString]; [attrString addAttribute:NSKernAttributeName value:@(((maxInteger - strLength) * rect.size.width)/(strLength - 1)) range:NSMakeRange(0, strLength)]; label.attributedText = attrString; }-(float)getLengthOfString:(NSString*)str { float strLength = 0; char *p = (char *)[str cStringUsingEncoding:NSUnicodeStringEncoding]; for (NSInteger i = 0 ; i < [str lengthOfBytesUsingEncoding:NSUnicodeStringEncoding]; i++) { if (*p) { strLength++; } p++; } return strLength/2; } //注:中文字符长度1,英文字符及数字长度0.5

22、运行时runtime获取某个类的成员变量
unsigned int count = 0; Ivar *ivars = class_copyIvarList([UITextField class], &count); for (int i = 0; i < count; i ++) { //取出成员变量 Ivar ivar = *(ivars + i); //打印成员变量 NSLog(@"%s",ivar_getName(ivar)); }

23、cell自动计算高度
1、首先的让cell的底部与挨着的子控件底部脱线建立关系; 2、设置估算高度 self.tableView.estimatedRowHeight = 70; 3、设置高度自动计算 self.tableView.rowHeight = UITableViewAutomaticDimension;

24、状态栏的样式
View controller-based status bar appearance 在info.plist里边添加它, value为NO,意思是说状态栏的样式更改不是基于控制器,而是由UIApplication决定;如果value=https://www.it610.com/article/YES 状态栏的样式有控制器决定。

25、导航控制器左边缘右滑动实现返回功能
如果修改了nav的leftBarButtonItem就没有此功能,如果需要此功能可以设置self.interactivePopGestureRecognizer.delegate = nil;

26、崩溃信息解析查找
先把xxx.app 和 xxx.dSYM 两个文件放在一个文件夹里,再根据crash的地址 ,用终端cd 到该文件夹,输入命令 atos -o xxx.app/xxx -arch arm64 0x113313131003 回车即可;

持续更新中...

    推荐阅读