前言
记录一些代码小技巧持续更新😜!
Objective-C tips
1、使控件从导航栏以下开始
self.edgesForExtendedLayout=UIRectEdgeNone;
2、将navigation返回按钮文字position设置不在屏幕上显示
[[UIBarButtonItem appearance] setBackButtonTitlePositionAdjustment:UIOffsetMake(NSIntegerMin, NSIntegerMin) forBarMetrics:UIBarMetricsDefault];
3、解决ScrollView等在viewController无法滚动到最顶部
//自动滚动调整,默认为YES
self.automaticallyAdjustsScrollViewInsets = NO;
4、隐藏navigationBar上返回按钮
[self.navigationController.navigationItem setHidesBackButton:YES];
[self.navigationItem setHidesBackButton:YES];
[self.navigationController.navigationBar.backItem setHidesBackButton:YES];
5、当tableView占不满一屏时,去除上下边多余的单元格
self.tableView.tableHeaderView = [UIView new];
self.tableView.tableFooterView = [UIView new];
6、显示完整的CellSeparator线
-(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
navigationController.hidesBarsOnSwipe = Yes;
8、将Navigationbar变成透明而不模糊
[self.navigationController.navigationBar setBackgroundImage:[UIImage new]
forBarMetrics:UIBarMetricsDefault];
self.navigationController.navigationBar .shadowImage = [UIImage new];
self.navigationController.navigationBar .translucent = YES;
9、NSString常用处理方法
//截取字符串
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 = @"我是 Tate-zwt";
replaceStr = [replaceStr stringByReplacingOccurrencesOfString:@" " 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方法即可:
- (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:
_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:
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代码和行间距?
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回根控制器视图
//这里也可以指定pop到哪个索引控制器
[self.navigationController popToViewController: [self.navigationController.viewControllers objectAtIndex: ([self.navigationController.viewControllers count] - 3)] animated:YES];
//或者
[self.navigationController popToRootViewControllerAnimated:YES];
15、dismiss回根控制器视图(PS:只能返回两层)
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?
NSMutableArray *vcArr = [self.navigationController.viewControllers mutableCopy];
[vcArr removeLastObject];
[vcArr addObject:loginVC];
[self.navigationController setViewControllers:vcArr animated:YES];
17、NSDictionary 怎么转成NSString
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:response.data options:0 error:0];
NSString *dataStr = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
18、获取系统可用存储空间 ,单位:字节
/**
* 获取系统可用存储空间
*
* @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 必须在主线程里执行
dispatch_async(dispatch_get_main_queue(), ^{
[weakSelf.webView stringByEvaluatingJavaScriptFromString:jsStr];
// [weakSelf.webView stringByEvaluatingJavaScriptFromString:[NSString stringWithFormat:@"alertTest('%@');", @"test"]];
});
20、获取相册图片的名称及后缀
#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 自动滑动到某一行
//四种枚举样式
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仓库,加一个参数可以省略这一步,然后速度就会提升不少。加参数的命令如下:
pod install --verbose --no-repo-update
pod update --verbose --no-repo-update
你可以 cd ~/.cocoapods/repos/ 到这个目录下 执行du -sh * 看下下载了多少
23、获取模拟器沙盒路径
NSArray *aryPath=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
//沙盒路劲
NSString *strDocPath=[aryPath objectAtIndex:0];
24、tableView.tableHeaderView 一些设置方法
_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、把需要改的约束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所有的子视图
[[someView subviews] makeObjectsPerformSelector:@selector(removeFromSuperview)];
27、将一个view放置在其兄弟视图的最上面
[parentView bringSubviewToFront:yourView]
28、将一个view放置在其兄弟视图的最下面
[parentView sendSubviewToBack:yourView]
29、layoutSubviews方法什么时候调用?
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的区别
isKindOfClass可以判断某个对象是否属于某个类,或者这个类的子类。
isMemberOfClass更加精准,它只能判断这个对象类型是否为这个类(不能判断子类)
31、IOS App开启iTunes文件共享(文稿)
通过在app工程的Info.plist文件中指定Application supports iTunes file sharing关键字,并将其值设置为YES。
我们可以很方便的打开app与iTunes之间的文件共享。
但这种共享有一个前提:App必须将任何所需要共享给用户的文件,都要存放在<Application_Home>/Documents目录下,<Application_Home>即在app安装时自动创建的app的主目录。
32、去掉UITabBar的分割线的方法
[[UITabBar appearance] setShadowImage:[UIImage new]];
[[UITabBar appearance] setBackgroundImage:[UIImage new]];