0%

iOS Develop Tips

前言

记录一些代码小技巧持续更新!

Xcode12模板位置:
1
/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/Library/Xcode/Templates/File Templates/iOS/Source/Cocoa Touch Class.xctemplate
Objective-C tips

1、使控件从导航栏以下开始

1
self.edgesForExtendedLayout=UIRectEdgeNone;

2、将navigation返回按钮文字position设置不在屏幕上显示

1
[[UIBarButtonItem appearance] setBackButtonTitlePositionAdjustment:UIOffsetMake(NSIntegerMin, NSIntegerMin) forBarMetrics:UIBarMetricsDefault];

3、解决ScrollView等在viewController无法滚动到最顶部

1
2
//自动滚动调整,默认为YES
self.automaticallyAdjustsScrollViewInsets = NO;

4、隐藏navigationBar上返回按钮

1
2
3
[self.navigationController.navigationItem setHidesBackButton:YES];
[self.navigationItem setHidesBackButton:YES];
[self.navigationController.navigationBar.backItem setHidesBackButton:YES];

5、当tableView占不满一屏时,去除上下边多余的单元格

1
2
self.tableView.tableHeaderView = [UIView new];
self.tableView.tableFooterView = [UIView new];

6、显示完整的CellSeparator线

1
2
3
4
5
6
7
8
9
10
11
12
-(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath{
if ([cell respondsToSelector:@selector(setSeparatorInset:)]) {
[cell setSeparatorInset:UIEdgeInsetsZero];
}
if ([cell respondsToSelector:@selector(setPreservesSuperviewLayoutMargins:)]) {
[cell setPreservesSuperviewLayoutMargins:NO];
}
if ([cell respondsToSelector:@selector(setLayoutMargins:)]) {
[cell setLayoutMargins:UIEdgeInsetsZero];
}
}

7、滑动的时候隐藏navigation bar

1
navigationController.hidesBarsOnSwipe = Yes;

8、将Navigationbar变成透明而不模糊

1
2
3
4
[self.navigationController.navigationBar setBackgroundImage:[UIImage new]
forBarMetrics:UIBarMetricsDefault];
self.navigationController.navigationBar .shadowImage = [UIImage new];
self.navigationController.navigationBar .translucent = YES;

9、NSString常用处理方法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
//截取字符串
NSString *interceptStr1 = @"Tate_zwt";
interceptStr1 = [interceptStr1 substringToIndex:3];//截取下标3之前的字符串
NSLog(@"截取的值为:%@",interceptStr1);//截取的值为:Tat

NSString *interceptStr2 = @"Tate_zwt";
NSRange rang = {3,1};
interceptStr2 = [interceptStr2 substringWithRange:rang];//截取rang范围的字符串
NSLog(@"截取的值为:%@",interceptStr2);//截取的值为:e

NSString *interceptStr3 = @"Tate_zwt";
interceptStr3 = [interceptStr3 substringFromIndex:3];//截取下标3之后的字符串
NSLog(@"截取的值为:%@",interceptStr3);//截取的值为:e_zwt


//匹配字符串
NSString *matchingStr = @"Tate_zwt";
NSRange range = [matchingStr rangeOfString:@"t"];//匹配得到的下标
NSLog(@"rang:%@",NSStringFromRange(range));//rang:{2, 1}
matchingStr = [matchingStr substringWithRange:range];//截取范围类的字符串
NSLog(@"截取的值为:%@",matchingStr);//截取的值为:t


//分割字符串
NSString *splitStr = @"Tate_zwt_zwt";
NSArray *array = [splitStr componentsSeparatedByString:@"_"]; //从字符A中分隔成2个元素的数组
NSLog(@"array:%@",array); //输出3个对象分别是:Tate,zwt,zwt


//拼接字符串
NSMutableString *appendStr = [NSMutableString string];
//使用逗号拼接
//[append appendFormat:@"%@zwt", append.length ? @"," : @""];
[appendStr appendString:@"我是"];
[appendStr appendString:@"Tate-zwt"];
NSLog(@"%@",appendStr);//输出:我是Tate-zwt


//替换字符串
NSString *replaceStr = @"我是&nbspTate-zwt";
replaceStr = [replaceStr stringByReplacingOccurrencesOfString:@"&nbsp" withString:@""];
NSLog(@"%@",replaceStr);//输出:我是Tate-zwt


//判断字符串内是否还包含特定的字符串(前缀,后缀)
NSString *hasStr = @"Tate.zwt";
[hasStr hasPrefix:@"Tate"] == 1 ? NSLog(@"YES") : NSLog(@"NO"); //前缀
[hasStr hasSuffix:@".zwt"] == 1 ? NSLog(@"YES") : NSLog(@"NO"); // 后缀


//字符串是否包含特定的字符
NSString *containStr = @"iOS Developer,喜欢做有趣的产品";
NSRange rangeDeveloper = [containStr rangeOfString:@"Developer"];
NSRange rangeProduct = [containStr rangeOfString:@"Product"];
rangeDeveloper.location != NSNotFound == 1 ? NSLog(@"YES") : NSLog(@"NO");
rangeProduct.location != NSNotFound == 1 ? NSLog(@"YES") : NSLog(@"NO");

10、UIPageControl如何改变点的大小?
重写setCurrentPage方法即可:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
- (void)setCurrentPage:(NSInteger)page {
[super setCurrentPage:page];
for (NSUInteger subviewIndex = 0; subviewIndex < [self.subviews count]; subviewIndex++) {
UIView *subview = [self.subviews objectAtIndex:subviewIndex];
UIImageView *imageView = nil;
if (subviewIndex == page) {
CGFloat w = 8;
CGFloat h = 8;
imageView = [[UIImageView alloc] initWithFrame:CGRectMake(-1.5, -1.5, w, h)];
imageView.image = [UIImage imageNamed:@"banner_red"];
[subview setFrame:CGRectMake(subview.frame.origin.x, subview.frame.origin.y, w, h)];
} else {
CGFloat w = 5;
CGFloat h = 5;
imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, w, h)];
imageView.image = [UIImage imageNamed:@"banner_gray"];
[subview setFrame:CGRectMake(subview.frame.origin.x, subview.frame.origin.y, w, h)];
}
imageView.tag = 10010;
UIImageView *lastImageView = (UIImageView *) [subview viewWithTag:10010];
[lastImageView removeFromSuperview]; //把上一次添加的view移除
[subview addSubview:imageView];
}
}

11、如何改变多行UILabel的行高?
Show me the code:

1
2
3
4
5
6
7
8
9
10
11
12
13
_promptLabel = [UILabel new];
NSString *labelText = @"Talk is cheap\nShow me the code";
_promptLabel.text = labelText;
_promptLabel.numberOfLines = 2;
_promptLabel.font = [UIFont systemFontOfSize:14];
NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:labelText];
NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
[paragraphStyle setLineSpacing:10]; //调整行间距
[attributedString addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:NSMakeRange(0, [labelText length])];
_promptLabel.attributedText = attributedString;
[_promptLabel sizeToFit];
[self.view addSubview:_promptLabel];

12、如何让Label等控件支持HTML格式的代码?
使用NSAttributedString:

1
2
3
NSString *htmlString = @"<div>Tate<span style='color:#1C86EE;'>《iOS Develop Tips》</span>get <span style='color:#1C86EE;'>Tate_zwt</span> 打赏 <span style='color:#FF3E96;'>100</span> 金币</div>";
NSAttributedString *attributedString = [[NSAttributedString alloc] initWithData:[htmlString dataUsingEncoding:NSUnicodeStringEncoding] options:@{ NSDocumentTypeDocumentAttribute : NSHTMLTextDocumentType } documentAttributes:nil error:nil];
_contentLabel.attributedText = attributedString;

13、如何让Label等控件同时支持HTML代码和行间距?

1
2
3
4
5
6
NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithData:[_open_bonus_article dataUsingEncoding:NSUnicodeStringEncoding] options:@{ NSDocumentTypeDocumentAttribute : NSHTMLTextDocumentType } documentAttributes:nil error:nil];
NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
[paragraphStyle setLineSpacing:12]; //调整行间距
[attributedString addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:NSMakeRange(0, [attributedString length])];
_detailLabel.attributedText = attributedString;
[_detailLabel sizeToFit];

14、pop回根控制器视图

1
2
3
4
//这里也可以指定pop到哪个索引控制器
[self.navigationController popToViewController: [self.navigationController.viewControllers objectAtIndex: ([self.navigationController.viewControllers count] - 3)] animated:YES];
//或者
[self.navigationController popToRootViewControllerAnimated:YES];

15、dismiss回根控制器视图(PS:只能返回两层)

1
2
3
4
5
6
7
8
9
10
11
12
13
if ([self respondsToSelector:@selector(presentingViewController)]){
self.presentingViewController.view.alpha = 0;
[self.presentingViewController.presentingViewController dismissViewControllerAnimated:YES completion:nil];
}else {
self.parentViewController.view.alpha = 0;
[self.parentViewController.parentViewController dismissViewControllerAnimated:YES completion:nil];
}
//或者
if ([self respondsToSelector:@selector(presentingViewController)]){
[self.presentingViewController.presentingViewController dismissViewControllerAnimated:YES completion:nil];
}else {
[self.parentViewController.parentViewController dismissViewControllerAnimated:YES completion:nil];
}

16、两个控制器怎么无限push?

1
2
3
4
NSMutableArray *vcArr = [self.navigationController.viewControllers mutableCopy];
[vcArr removeLastObject];
[vcArr addObject:loginVC];
[self.navigationController setViewControllers:vcArr animated:YES];

17、NSDictionary 怎么转成NSString

1
2
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:response.data options:0 error:0];
NSString *dataStr = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];

18、获取系统可用存储空间 ,单位:字节

1
2
3
4
5
6
7
8
9
10
/**
* 获取系统可用存储空间
*
* @return 系统空用存储空间,单位:字节
*/
-(NSUInteger)systemFreeSpace{
NSString *docPath=[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
NSDictionary *dict=[[NSFileManager defaultManager] attributesOfFileSystemForPath:docPath error:nil];
return [[dict objectForKey:NSFileSystemFreeSize] integerValue];
}

19、有时OC调用JS代码没反应?
stringByEvaluatingJavaScriptFromString 必须在主线程里执行

1
2
3
4
dispatch_async(dispatch_get_main_queue(), ^{
[weakSelf.webView stringByEvaluatingJavaScriptFromString:jsStr];
// [weakSelf.webView stringByEvaluatingJavaScriptFromString:[NSString stringWithFormat:@"alertTest('%@');", @"test"]];
});

20、获取相册图片的名称及后缀

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#pragma mark UIImagePickerControllerDelegate
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info{
//获取图片的名字
__block NSString* fileName;
NSURL *imageURL = [info valueForKey:UIImagePickerControllerReferenceURL];
ALAssetsLibraryAssetForURLResultBlock resultblock = ^(ALAsset *myasset)
{
ALAssetRepresentation *representation = [myasset defaultRepresentation];
fileName = [representation filename];
NSLog(@"fileName : %@",fileName);
self.imageFileName = fileName;
};

ALAssetsLibrary* assetslibrary = [[ALAssetsLibrary alloc] init];
[assetslibrary assetForURL:imageURL
resultBlock:resultblock
failureBlock:nil];
}

21、UITableView 自动滑动到某一行

1
2
3
4
5
6
7
8
9
10
11
//四种枚举样式
UITableViewScrollPositionNone,
UITableViewScrollPositionTop,
UITableViewScrollPositionMiddle,
UITableViewScrollPositionBottom

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
//第一种方法
[tableView scrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewScrollPositionTop animated:YES];
//第二种方法
[self.tableVieW selectRowAtIndexPath:indexPath animated:YES scrollPosition:UITableViewScrollPositionTop];

22、 Xcode8注释快捷键不能使用的解决方法:
In Terminal: sudo /usr/libexec/xpccachectl

最近使用CocoaPods来添加第三方类库,无论是执行pod install还是pod update都卡在了Analyzing dependencies不动
原因在于当执行以上两个命令的时候会升级CocoaPods的spec仓库,加一个参数可以省略这一步,然后速度就会提升不少。加参数的命令如下:

1
2
pod install --verbose --no-repo-update
pod update --verbose --no-repo-update

你可以 cd ~/.cocoapods/repos/ 到这个目录下 执行du -sh * 看下下载了多少

23、获取模拟器沙盒路径

1
2
3
NSArray *aryPath=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
//沙盒路劲
NSString *strDocPath=[aryPath objectAtIndex:0];

24、tableView.tableHeaderView 一些设置方法

1
2
3
4
5
6
7
8
9
10
11
    _tableView.tableHeaderView = _heatOrTimeView;
[_heatOrTimeView mas_makeConstraints:^(MASConstraintMaker *make) {
make.left.right.top.equalTo(_tableView);
make.width.equalTo(_tableView);
make.height.mas_equalTo(@36);
}];
// 如果是动态改变高度的话这里要加上以下代码
// [_tableView layoutIfNeeded];
// [_tableView beginUpdates]; 这个是增加动画效果
// [_tableView endUpdates];
// _tableView.tableHeaderView = _heatOrTimeView;

25、约束如何做UIView动画?

1
2
3
4
5
6
7
8
9
1、把需要改的约束Constraint拖条线出来,成为属性
2、在需要动画的地方加入代码,改变此属性的constant属性
3、开始做UIView动画,动画里边调用layoutIfNeeded方法

@property (weak, nonatomic) IBOutlet NSLayoutConstraint *buttonTopConstraint;
self.buttonTopConstraint.constant = 100;
[UIView animateWithDuration:.5 animations:^{
[self.view layoutIfNeeded];
}];

26、删除某个view所有的子视图

1
[[someView subviews] makeObjectsPerformSelector:@selector(removeFromSuperview)];

27、将一个view放置在其兄弟视图的最上面

1
[parentView bringSubviewToFront:yourView]

28、将一个view放置在其兄弟视图的最下面

1
[parentView sendSubviewToBack:yourView]

29、layoutSubviews方法什么时候调用?

1
2
3
4
5
6
1、init方法不会调用
2、addSubview方法等时候会调用
3、bounds改变的时候调用
4、scrollView滚动的时候会调用scrollView的layoutSubviews方法(所以不建议在scrollView的layoutSubviews方法中做复杂逻辑)
5、旋转设备的时候调用
6、子视图被移除的时候调用参考请看:[http://blog.logichigh.com/2011/03/16/when-does-layoutsubviews-get-called/](http://blog.logichigh.com/2011/03/16/when-does-layoutsubviews-get-called/)

30、isKindOfClass和isMemberOfClass的区别

1
2
isKindOfClass可以判断某个对象是否属于某个类,或者这个类的子类。
isMemberOfClass更加精准,它只能判断这个对象类型是否为这个类(不能判断子类)

31、IOS App开启iTunes文件共享(文稿)

1
2
3
通过在app工程的Info.plist文件中指定Application supports iTunes file sharing关键字,并将其值设置为YES。
我们可以很方便的打开app与iTunes之间的文件共享。
但这种共享有一个前提:App必须将任何所需要共享给用户的文件,都要存放在<Application_Home>/Documents目录下,<Application_Home>即在app安装时自动创建的app的主目录。

32、去掉UITabBar的分割线的方法

1
2
[[UITabBar appearance] setShadowImage:[UIImage new]];
[[UITabBar appearance] setBackgroundImage:[UIImage new]];

33、URLWithString:(NSString *)str relativeToURL:(NSURL *)baseURL中baseURL拼接字段的问题
问题描述
URLWithString:(NSString *)str relativeToURL:(NSURL *)baseURL中baseURL结尾字段的相关问题拼接后被去掉的问题,情况如下:

1
2
3
4
NSURL *baseUrl = [NSURL URLWithString:@"http://test.com/v1"];
NSLog(@"%@", baseUrl);
NSURL *newURL = [NSURL URLWithString:@"/test/get_all" relativeToURL: baseUrl];
NSLog(@"newURL:%@",[newURL absoluteString]);//http://test.com/test/get_all

其中v1字符串拼接后被去掉了
解决办法:
直接让baseUrl已/符号结尾

1
2
3
4
NSURL *baseUrl = [NSURL URLWithString:@"http://test.com/v1/"];
NSLog(@"%@", baseUrl);
NSURL *newURL = [NSURL URLWithString:@"test/get_all" relativeToURL: baseUrl];
NSLog(@"newURL:%@",[newURL absoluteString]);//http://test.com/v1/test/get_all

34、URL编码 、解码
编码:iOS中http请求遇到汉字的时候,需要转化成UTF-8,用到的方法是:

1
NSString *result = [sns_info stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLPathAllowedCharacterSet]];

解码:请求后,返回的数据,如何显示的是这样的格式:%3A%2F%2F,此时需要我们进行UTF-8解码,用到的方法是:

1
NSString *resultData = result.stringByRemovingPercentEncoding;

35、reactiveCocoa rac_signalForControlEvents多次触发解决方法
原因:
我们知道cell在移出屏幕时并没有被销毁,而是到了一个重用池中,放到池子前我们已经做了[[cell.btn rac_signalForControlEvents:UIControlEventTouchUpInside]subscribeNext:^(idx) {}];
,取不到的话再创建。所以取出来的cell极有可能是池子里的,取出来之后再进行上述的rac_signalForControlEvents操作,导致每rac_signalForControlEvents多少次操,点击按钮时,事件就被触发多少次!
此时就得通过takeUntil:someSignal来终止cell.btn之前的signal了:
解决:

1
2
[[_cell.btn rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
}];

换成

1
2
[[[cell.deleteBtn rac_signalForControlEvents:UIControlEventTouchUpInside] takeUntil:cell.rac_prepareForReuseSignal] subscribeNext:^(__kindof UIControl * _Nullable x) {
}];

36、一个Label 显示两种颜色的写法

1
2
3
4
5
6
NSAttributedString *commentCountAttrString = [[NSAttributedString alloc] initWithString:@"回复:" attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:14],NSForegroundColorAttributeName:CFontColor3}];
NSMutableAttributedString *commentAttrString = [[NSMutableAttributedString alloc] initWithString:_messageModel.content attributes:@{NSFontAttributeName:[UIFont boldSystemFontOfSize:14],NSForegroundColorAttributeName:CFontColor5}];
NSMutableAttributedString *commentString = [[NSMutableAttributedString alloc] init];
[commentString appendAttributedString: commentCountAttrString];
[commentString appendAttributedString: commentAttrString];
_replyLabel.attributedText = commentString;

37、解决iPhone 横屏启动界面错乱的问题
在AppDelegate中,在didFinishLaunchingWithOptions方法中创建window前先加入:

1
application.statusBarOrientation = UIInterfaceOrientationPortrait;

38、iPhone 屏幕亮度

1
2
3
4
//获取系统屏幕当前的亮度值
CGFloat value = [UIScreen mainScreen].brightness;
//设置系统屏幕的亮度值
[[UIScreen mainScreen] setBrightness:value];

38、如何让在UIScrollView的vc移动时也能调用生命周期?
手动调用VC的生命周期:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
NSInteger currentIndex = contentOffset.x/self.frame.size.width;
UIViewController *oldVC = nil;
if (currentIndex != -1) {
oldVC = _viewsArray[currentIndex];
}
UIViewController *newsVc = _viewsArray[currentIndex];
if (newsVc.view.superview) {//调用生命周期函数(如viewwillappear等)
if (oldVC) {
[newsVc beginAppearanceTransition:NO animated:YES];
[newsVc endAppearanceTransition];
}
[newsVc beginAppearanceTransition:YES animated:YES];
[newsVc endAppearanceTransition];
}

39、常用C语言函数

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
一.随机数:

1.rand();

范围: 0-无穷大.

特点: 仅第一次随机,其他次都是和第一次相同.常用于调试.

返回值: long

实例: int ran = rand();

2.random();

范围: 0-无穷大.

特点: 每次都随机出现一个数字

返回值: long

二: 绝对值:

1.abs(int);

特点: 整数的绝对值

返回值: int

实例: int ab = abs(-1);

2.fabs(double);

特点: 浮点数的绝对值

返回值: double

实例: double fab = fabs(-12.345);

三: 取整

1.trunc(double);

特点: 直接取整

返回值: double

实例: double tru = trunc(3.444);

2.ceil(double)

特点: 向上取整 (舍弃小数点部分,往个位数进1)

返回值: double

实例: double ce = ceil(12.345);

3.floor(double);

特点: 向下取整 (舍弃小数点部分)

返回值: double

实例: double flo = floor(12.345);

4.四舍五入

实现方法:巧妙的利用取整规则

说明: a是要四舍五入的数,b是结果

(1)如果取整的是正数:

CGFloat a = 1.5;

int b = (int)(a + 0.5);

(2)如果取整的是负数:

CGFloat a = -1.5;

int b = (int)(a - 0.5);

5.浮点数提取整数和小数

double fraction,integer;

double number = 100000.567;

fraction = modf(number, &integer);

printf("The whole and fractional parts of %lf are %lf and %lf",number, integer, fraction);

四: 算数相关

1.pow(double, double);

特点: 求a的b次方

返回值: double

实例: double po = pow(2, 3);

2.sqrt(double)

特点: 求平方根

返回值: double

实例: double sqr = sqrt(2);

五:圆周率

M_PI == π

M_PI_2 == π/2

M_PI_4 == π/4

M_1_PI == 1/π

M_2_PI == 1/2

六.比较大小

1.MAX(1, 2); 返回最大值

2.MIN(2, 1); 返回最小值

3.ABS(-2); 返回绝对值

40、UILable 样式自定义(同一个Label展示不同颜色,字体)

1
2
3
4
5
6
7
8
9
10
11
12
//拼接字符串
NSMutableString *appendStr = [NSMutableString string];
[appendStr appendString:@"摘要:"];
[appendStr appendString:_movies.editor_note];

NSMutableAttributedString *noteStr = [YYPublicTools load_attributedString:appendStr font:FFont4 color:CFontColor4 Alignment:NSTextAlignmentLeft];
NSRange redRange = NSMakeRange([[noteStr string] rangeOfString:@"摘要:"].location, [[noteStr string] rangeOfString:@"摘要:"].length);
//需要设置的位置
[noteStr addAttribute:NSForegroundColorAttributeName value:CFontColor3 range:redRange];
[noteStr addAttribute:NSFontAttributeName value:[UIFont boldSystemFontOfSize:14] range:redRange];
//设置
_authorSayLabel.attributedText = noteStr;
1
2
3
4
5
6
7
8
9
10
11
12
+ (NSMutableAttributedString *)load_attributedString:(NSString *)string font:(UIFont *)font color:(UIColor *)color Alignment:(NSTextAlignment )Alignment{
NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithData:[string dataUsingEncoding:NSUnicodeStringEncoding] options:@{} documentAttributes:nil error:nil];

NSMutableParagraphStyle * paragraphStyle1 = [[NSMutableParagraphStyle alloc] init];
[paragraphStyle1 setLineSpacing:7];
[paragraphStyle1 setAlignment:Alignment];
NSDictionary *attributeDict = [NSDictionary dictionaryWithObjectsAndKeys:
font,NSFontAttributeName,
paragraphStyle1,NSParagraphStyleAttributeName,color,NSForegroundColorAttributeName,nil];
[attributedString addAttributes:attributeDict range:NSMakeRange(0, [attributedString length])];
return attributedString;
}

41、解决IQKeyboardManager在UITableviewCell中TextField或者TextView不起作用的问题。
框架本身不支持所以只能用代码解决:
1.首先在- (void)viewDidLoad中调用对键盘实现监听

1
2
[[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
[[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];

2.然后调用通知的方法:

1
2
3
4
5
6
7
8
9
10
11
#pragma mark 键盘出现
-(void)keyboardWillShow:(NSNotification *)note
{
CGRect keyBoardRect=[note.userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue];
self.tableView.contentInset = UIEdgeInsetsMake(0, 0, keyBoardRect.size.height, 0);
}
#pragma mark 键盘消失
-(void)keyboardWillHide:(NSNotification *)note
{
self.tableView.contentInset = UIEdgeInsetsZero;
}

42、去除字符串首尾空格、换行

1
2
3
//去除首尾空格和换行 
//NSCharacterSet 多个枚举选择
NSString *content = [textView.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];

43、autolayout进阶

1
2
3
4
5
6
7
1.Content Hugging Priority

视图抗拉伸优先级, 值越小,视图越容易被拉伸,

2. Content Compression Resistance Priority:

视图抗压缩优先级, 值越小,视图越容易被压缩,

44、pod 单独安装一个新添加的库
这将安装新项目而不更新现有的repos
pod install --no-repo-update

45、iOS-限制UILabel宽度自适应的最大宽度

1
2
3
_userNameLabel.preferredMaxLayoutWidth = 170 * kScaleWidth; //设置多行label最大宽度,只在 numberOfLines = 0 生效
_userNameLabel.numberOfLines = 0; //可在xib 或者 Sb设置
_userNameLabel.height = 20; // 让他固定只能一行的高度 可在xib 或者 Sb设置