iOS学习笔记之开发实用小技巧(持续更新)
2017-07-03 15:54
656 查看
解决同时按两个按钮进入两个View的问题
[button setExclusiveTouch:YES];
在6p模拟器上输出宽度是414,在6p真机上输出是375。是测试机本身设置的问题,到 设置->显示与亮度->显示模式,改为“标准”
修改tableViewCell选中状态的颜色
cell.selectedBackgroundView = [[UIView alloc] initWithFrame: cell.frame]; cell.selectedBackgroundView.backgroundColor = [UIColor whiteColor];
默认选中第一个cell
NSInteger selectedIndex = 0; NSIndexPath *selectedIndexPath = [NSIndexPath indexPathForRow:selectedIndex inSection:0]; [self.tableView selectRowAtIndexPath:selectedIndexPath animated:NO scrollPosition:UITableViewScrollPositionNone];
修改textFieldplaceholder字体颜色和大小
textField.placeholder = @"iOS"; [textField setValue:[UIColor redColor] forKeyPath:@"_placeholderLabel.textColor"]; [textField setValue:[UIFont boldSystemFontOfSize:16] forKeyPath:@"_placeholderLabel.font"];
关于右滑返回上一级
自定义leftBarButtonItem后无法启用系统自带的右滑返回,可以设置一下代码:
self.navigationController.interactivePopGestureRecognizer.delegate = self;
取掉导航栏下边的黑线
[self.navigationController.navigationBar setBackgroundImage: [UIImage alloc]init]]; self.navigationController.navigationBar.shadowImage = [[UIImage alloc]init];
点击cell单元格的时候取消选中cell
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { self.tableView.deselectRowAtIndexPath(indexPath, animated: true) }
UITextField默认显示键盘
textField.becomeFirstResponder()
UIImage设置圆角
说到设置圆角,你是否首先想到的是:
self.iconImage.layer.cornerRadius = 20; self.iconImage.layer.masksToBounds = YES;
建议大家尽量不要这么设置, 因为使用图层过量会有卡顿现象, 特别是弄圆角或者阴影会很卡, 如果设置图片圆角我们一般用绘图来做:
/** 设置圆形图片(放到分类中使用) */ -(UIImage *)cutCircleImage { UIGraphicsBeginImageContextWithOptions(self.size, NO, 0.0); // 获取上下文 CGContextRef ctr = UIGraphicsGetCurrentContext(); // 设置圆形 CGRect rect = CGRectMake(0, 0, self.size.width, self.size.height); CGContextAddEllipseInRect(ctr, rect); // 裁剪 CGContextClip(ctr); // 将图片画上去 [self drawInRect:rect]; UIImage *image = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); return image; }
这个方法就是设置圆角图片, 效率很高, 不会造成卡顿现象, 大家要把这个方法单独放到分类中使用
磁盘总空间大小
1.获取磁盘总空间大小
//磁盘总空间 +(CGFloat)diskOfAllSizeMBytes{ CGFloat size = 0.0; NSError *error; NSDictionary *dic = [[NSFileManager defaultManager]attributesOfFileSystemForPath:NSHomeDirectory() error:&error]; if (error) { #ifdef DEBUG NSLog(@"error: %@", error.localizedDescription); #endif }else{ NSNumber *number = [dic objectForKey:NSFileSystemSize]; size = [number floatValue]/1024/1024; } return size; }
2.获取磁盘可用空间大小
//磁盘可用空间 +(CGFloat)diskOfFreeSizeMBytes{ CGFloat size = 0.0; NSError *error; NSDictionary *dic = [[NSFileManager defaultManager] attributesOfFileSystemForPath:NSHomeDirectory() error:&error]; if (error) { #ifdef DEBUG NSLog(@"error: %@", error.localizedDescription); #endif }else{ NSNumber *number = [dic objectForKey:NSFileSystemFreeSize]; size = [number floatValue]/1024/1024; } return size; }
3.获取指定路径下某个文件的大小
//获取文件大小 +(long long)fileSizeAtPath:(NSString *)filePath{ NSFileManager *fileManager = [NSFileManager defaultManager]; if (![fileManager fileExistsAtPath:filePath]) return 0; return [[fileManager attributesOfItemAtPath:filePath error:nil] fileSize]; }
4.获取文件夹下所有文件的大小
//获取文件夹下所有文件的大小 +(long long)folderSizeAtPath:(NSString *)folderPath{ NSFileManager *fileManager = [NSFileManager defaultManager]; if (![fileManager fileExistsAtPath:folderPath]) return 0; NSEnumerator *filesEnumerator = [[fileManager subpathsAtPath:folderPath] objectEnumerator]; NSString *fileName; long long folerSize = 0; while ((fileName = [filesEnumerator nextObject]) != nil) { NSString *filePath = [folderPath stringByAppendingPathComponent:fileName]; folerSize += [self fileSizeAtPath:filePath]; } return folerSize; }
NSString处理
--获取字符串(或汉字)首字母
//获取字符串(或汉字)首字母 +(NSString *)firstCharacterWithString:(NSString *)string{ NSMutableString *str = [NSMutableString stringWithString:string]; CFStringTransform((CFMutableStringRef)str, NULL, kCFStringTransformMandarinLatin, NO); CFStringTransform((CFMutableStringRef)str, NULL, kCFStringTransformStripDiacritics, NO); NSString *pingyin = [str capitalizedString]; return [pingyin substringToIndex:1]; }
--字符串反转
-(NSString*)reverseWordsInString:(NSString*)str { NSMutableString *reverString = [NSMutableString stringWithCapacity:str.length]; [str enumerateSubstringsInRange:NSMakeRange(0, str.length) options:NSStringEnumerationReverse | NSStringEnumerationByComposedCharacterSequences usingBlock:^(NSString *substring, NSRange substringRange, NSRange enclosingRange, BOOL *stop) { [reverString appendString:substring]; }]; return reverString; }
--字符串按多个符号分割
NSString *str = @“abc,def.ghi” NSCharacterSet *set = [NSCharacterSet characterSetWithCharactersInString:@“,.”]; NSLog(@“%@”,[str componentsSeparatedByCharactersInSet:set]);
--获取汉字的拼音
+(NSString *)transform:(NSString *)chinese { //将NSString装换成NSMutableString NSMutableString *pinyin = [chinese mutableCopy]; //将汉字转换为拼音(带音标) CFStringTransform((__bridge CFMutableStringRef)pinyin, NULL, kCFStringTransformMandarinLatin, NO); NSLog(@"%@", pinyin); //去掉拼音的音标 CFStringTransform((__bridge CFMutableStringRef)pinyin, NULL, kCFStringTransformStripCombiningMarks, NO); NSLog(@"%@", pinyin); //返回最近结果 return pinyin; }
--字符串中是否含有中文
+(BOOL)checkIsChinese:(NSString *)string { for (int i=0; i<string.length; i++) { unichar ch = [string characterAtIndex:i]; if (0x4E00 <= ch && ch <= 0x9FA5) { return YES; } } return NO; }
UILabel修改行距,首行缩进
1.UILabel修改文字行距,首行缩进 lineSpacing: 行间距 firstLineHeadIndent:首行缩进 font: 字体 textColor: 字体颜色 - (NSDictionary *)settingAttributesWithLineSpacing:(CGFloat)lineSpacing FirstLineHeadIndent:(CGFloat)firstLineHeadIndent Font:(UIFont *)font TextColor:(UIColor *)textColor{ //分段样式 NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init]; //行间距 paragraphStyle.lineSpacing = lineSpacing; //首行缩进 paragraphStyle.firstLineHeadIndent = firstLineHeadIndent; //富文本样式 NSDictionary *attributeDic = @{ NSFontAttributeName : font, NSParagraphStyleAttributeName : paragraphStyle, NSForegroundColorAttributeName : textColor }; return attributeDic; }
删除NSUserDefaults所有记录
第一种:
NSString *appDomain = [[NSBundle mainBundle] bundleIdentifier]; [[NSUserDefaults standardUserDefaults] removePersistentDomainForName:appDomain];
第二种:
-(void)resetDefaults { NSUserDefaults * defs = [NSUserDefaults standardUserDefaults]; NSDictionary * dict = [defs dictionaryRepresentation]; for (id key in dict) { [defs removeObjectForKey:key]; } [defs synchronize]; }
禁止锁屏
默认情况下,当设备一段时间没有触控动作时,iOS会锁住屏幕。但有一些应用是不需要锁屏的,比如视频播放器。
[UIApplication sharedApplication].idleTimerDisabled = YES; 或 [[UIApplication sharedApplication] setIdleTimerDisabled:YES];
隐藏/显示文件
//显示 defaults write com.apple.finder AppleShowAllFiles -bool true killall Finder //隐藏 defaults write com.apple.finder AppleShowAllFiles -bool false killall Finder
iOS跳转到App Store下载应用评分
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"itms-apps://itunes.apple.com/WebObjects/MZStore.woa/wa/viewContentsUserReviews?type=Purple+Software&id=APPID"]];
iOS在当前屏幕获取第一响应
UIWindow * keyWindow = [[UIApplication sharedApplication] keyWindow]; UIView * firstResponder = [keyWindow performSelector:@selector(firstResponder)];
NSArray 快速求总和 最大值 最小值 和 平均值
NSArray *array = [NSArray arrayWithObjects:@"2.0", @"2.3", @"3.0", @"4.0", @"10", nil]; CGFloat sum = [[array valueForKeyPath:@"@sum.floatValue"] floatValue]; CGFloat avg = [[array valueForKeyPath:@"@avg.floatValue"] floatValue]; CGFloat max =[[array valueForKeyPath:@"@max.floatValue"] floatValue]; CGFloat min =[[array valueForKeyPath:@"@min.floatValue"] floatValue]; NSLog(@"%f\n%f\n%f\n%f",sum,avg,max,min);
关于NSDateFormatter的格式
G: 公元时代,例如AD公元 yy: 年的后2位 yyyy: 完整年 MM: 月,显示为1-12 MMM: 月,显示为英文月份简写,如 Jan MMMM: 月,显示为英文月份全称,如 Janualy dd: 日,2位数表示,如02 d: 日,1-2位显示,如 2 EEE: 简写星期几,如Sun EEEE: 全写星期几,如Sunday aa: 上下午,AM/PM H: 时,24小时制,0-23 K:时,12小时制,0-11 m: 分,1-2位 mm: 分,2位 s: 秒,1-2位 ss: 秒,2位 S: 毫秒
阿拉伯数字转中文格式
+(NSString *)translation:(NSString *)arebic { NSString *str = arebic; NSArray *arabic_numerals = @[@"1",@"2",@"3",@"4",@"5",@"6",@"7",@"8",@"9",@"0"]; NSArray *chinese_numerals = @[@"一",@"二",@"三",@"四",@"五",@"六",@"七",@"八",@"九",@"零"]; NSArray *digits = @[@"个",@"十",@"百",@"千",@"万",@"十",@"百",@"千",@"亿",@"十",@"百",@"千",@"兆"]; NSDictionary *dictionary = [NSDictionary dictionaryWithObjects:chinese_numerals forKeys:arabic_numerals]; NSMutableArray *sums = [NSMutableArray array]; for (int i = 0; i < str.length; i ++) { NSString *substr = [str substringWithRange:NSMakeRange(i, 1)]; NSString *a = [dictionary objectForKey:substr]; NSString *b = digits[str.length -i-1]; NSString *sum = [a stringByAppendingString:b]; if ([a isEqualToString:chinese_numerals[9]]) { if([b isEqualToString:digits[4]] || [b isEqualToString:digits[8]]) { sum = b; if ([[sums lastObject] isEqualToString:chinese_numerals[9]]) { [sums removeLastObject]; } }else { sum = chinese_numerals[9]; } if ([[sums lastObject] isEqualToString:sum]) { continue; } } [sums addObject:sum]; } NSString *sumStr = [sums componentsJoinedByString:@""]; NSString *chinese = [sumStr substringToIndex:sumStr.length-1]; NSLog(@"%@",str); NSLog(@"%@",chinese); return chinese; }
CocoaPods pod install/pod update更新慢的问题
pod install --verbose --no-repo-update pod update --verbose --no-repo-update 如果不加后面的参数,默认会升级CocoaPods的spec仓库,加一个参数可以省略这一步,然后速度就会提升不少
UIView设置部分圆角
你是不是也遇到过这样的问题,一个button或者label,只要右边的两个角圆角,或者只要一个圆角。该怎么办呢。这就需要图层蒙版来帮助我们了
CGRect rect = view.bounds; CGSize radio = CGSizeMake(30, 30);//圆角尺寸 UIRectCorner corner = UIRectCornerTopLeft|UIRectCornerTopRight;//这只圆角位置 UIBezierPath *path = [UIBezierPath bezierPathWithRoundedRect:rect byRoundingCorners:corner cornerRadii:radio]; CAShapeLayer *masklayer = [[CAShapeLayer alloc]init];//创建shapelayer masklayer.frame = view.bounds; masklayer.path = path.CGPath;//设置路径 view.layer.mask = masklayer;
取上整与取下整
floor(x),有时候也写做Floor(x),其功能是“下取整”,即取不大于x的最大整数 例如: x=3.14,floor(x)=3 y=9.99999,floor(y)=9 与floor函数对应的是ceil函数,即上取整函数。 ceil函数的作用是求不小于给定实数的最小整数。 ceil(2)=ceil(1.2)=cei(1.5)=2.00 floor函数与ceil函数的返回值均为double型
去掉导航栏返回的back标题
[[UIBarButtonItemappearance]setBackButtonTitlePositionAdjustment:UIOffsetMake(0, -60)forBarMetrics:UIBarMetricsDefault];
navigationBar变为纯透明
//第一种方法 //导航栏纯透明 [self.navigationBar setBackgroundImage:[UIImage new] forBarMetrics:UIBarMetricsDefault]; //去掉导航栏底部的黑线 self.navigationBar.shadowImage = [UIImage new]; //第二种方法 [[self.navigationBar subviews] objectAtIndex:0].alpha = 0;
tabBar同理
[self.tabBar setBackgroundImage:[UIImage new]]; self.tabBar.shadowImage = [UIImage new];
navigationBar根据滑动距离的渐变色实现
第一种:
-(void)scrollViewDidScroll:(UIScrollView *)scrollView { CGFloat offsetToShow = 200.0;//滑动多少就完全显示 CGFloat alpha = 1 - (offsetToShow - scrollView.contentOffset.y) / offsetToShow; [[self.navigationController.navigationBar subviews] objectAtIndex:0].alpha = alpha; }
第二种:
-(void)scrollViewDidScroll:(UIScrollView *)scrollView { CGFloat offsetToShow = 200.0; CGFloat alpha = 1 - (offsetToShow - scrollView.contentOffset.y) / offsetToShow; [self.navigationController.navigationBar setShadowImage:[UIImage new]]; [self.navigationController.navigationBar setBackgroundImage:[self imageWithColor:[[UIColor orangeColor]colorWithAlphaComponent:alpha]] forBarMetrics:UIBarMetricsDefault]; } //生成一张纯色的图片 -(UIImage *)imageWithColor:(UIColor *)color { CGRect rect = CGRectMake(0.0f, 0.0f, 1.0f, 1.0f); UIGraphicsBeginImageContext(rect.size); CGContextRef context = UIGraphicsGetCurrentContext(); CGContextSetFillColorWithColor(context, [color CGColor]); CGContextFillRect(context, rect); UIImage *theImage = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); return theImage; }
iOS开发中一些相关的路径
模拟器的位置: /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs 文档安装位置: /Applications/Xcode.app/Contents/Developer/Documentation/DocSets 插件保存路径: ~/Library/ApplicationSupport/Developer/Shared/Xcode/Plug-ins 自定义代码段的保存路径: ~/Library/Developer/Xcode/UserData/CodeSnippets/ 如果找不到CodeSnippets文件夹,可以自己新建一个CodeSnippets文件夹。 描述文件路径 ~/Library/MobileDevice/Provisioning Profiles
dispatch_group的使用
dispatch_group_t dispatchGroup = dispatch_group_create(); dispatch_group_enter(dispatchGroup); dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{ NSLog(@"第一个请求完成"); dispatch_group_leave(dispatchGroup); }); dispatch_group_enter(dispatchGroup); dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(10 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{ NSLog(@"第二个请求完成"); dispatch_group_leave(dispatchGroup); }); dispatch_group_notify(dispatchGroup, dispatch_get_main_queue(), ^(){ NSLog(@"请求完成"); });
相关文章推荐
- ios学习--iphone开发笔记和技巧总结(原址持续更新)
- iOS学习笔记33-iOS 开发博客合集(持续更新中。。。)
- ios学习--iphone开发笔记和技巧总结(原址持续更新)
- Python开发实战学习笔记(持续更新)
- iOS学习之——开发中常见的英文词汇(持续更新,英文不好的同学可以参考下)
- iOS 开发学习资料整理(持续更新)
- iOS 开发实用工具(持续更新)
- iOS学习笔记总结一(持续更新)
- 游戏开发流程与思想学习笔记(持续更新)
- iOS开发小技巧(持续更新中)
- [IOS开发中使用的小技巧]xcode实用快捷键(更新中)
- iOS学习笔记62- iOS开发小技巧之--WeakSelf宏的进化
- iOS开发中一些实用小代码(持续更新-2016年11月7日)
- iOS开发中总结的小技巧(持续更新中)
- iOS 开发 - Swift 全面系统的学习(持续更新...)
- 在这里总结一些iOS开发中的小技巧,能大大方便我们的开发,持续更新。
- iOS 开发学习资料整理(持续更新)
- Ios 开发实用工具(持续更新)
- iOS学习笔记总结二(持续更新)
- 一些实用的DBA语句(持续学习,持续更新)