引言
好久没写blog了,最近映客游戏直播相关的工作告一个段落,抽出些时间写个blog,和大家分享一下平时开发中使用过的一些小技巧,希望大家能帮着一起补充。
实用小技巧
通过多个符号进行分割字符串
123NSString *str = @"abcd,efg,hijk;lmn.opq";NSCharacterSet *set = [NSCharacterSet characterSetWithCharactersInString:@",;."];NSLog(@"%@",[str componentsSeparatedByCharactersInSet:set]);
判断View是不是指定视图的子视图
1BOOL isView = [textView isDescendantOfView:self.view];
修改UITextField中Placeholder的字体颜色、大小
12[self.textField setValue:[UIColor redColor] forKeyPath:@"_placeholderLabel.textColor"];[self.textField setValue:[UIFont boldSystemFontOfSize:16] forKeyPath:@"_placeholderLabel.font"];
获取 UIImage 占用的内存大小
12UIImage *image = [UIImage imageNamed:@"abc"];NSUInteger size = CGImageGetHeight(image.CGImage) * CGImageGetBytesPerRow(image.CGImage);
GCD 定时器
1234567dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);dispatch_source_t timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0,queue);dispatch_source_set_timer(timer,dispatch_walltime(NULL, 0),1.0*NSEC_PER_SEC, 0); //每秒执行dispatch_source_set_event_handler(timer, ^{//执行定时器代码});dispatch_resume(timer);
浮点数取整
1234CGFloat x;(int)x : 强转为整形,四舍五入floor(x) : 向下取整ceil(x) : 向上取整。
给UIView设置背景图片
12UIImage *image = [UIImage imageNamed:@"image"];self.myView.layer.contents = (__bridge id _Nullable)(image.CGImage);
给UIView设置部分圆角(只要右边的两个角圆角,或者只要一个圆角,通过蒙版实现)
12345678CGRect 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];//创建shapelayermasklayer.frame = view.bounds;masklayer.path = path.CGPath;//设置路径view.layer.mask = masklayer;
防止scrollView手势覆盖侧滑手势
1[scrollView.panGestureRecognizerrequireGestureRecognizerToFail:self.navigationController.interactivePopGestureRecognizer];
去掉导航栏返回的back标题
1[[UIBarButtonItemappearance]setBackButtonTitlePositionAdjustment:UIOffsetMake(0, -60)forBarMetrics:UIBarMetricsDefault];
动画暂停再开始
12345678910111213141516-(void)pauseLayer:(CALayer *)layer{CFTimeInterval pausedTime = [layer convertTime:CACurrentMediaTime() fromLayer:nil];layer.speed = 0.0;layer.timeOffset = pausedTime;}-(void)resumeLayer:(CALayer *)layer{CFTimeInterval pausedTime = [layer timeOffset];layer.speed = 1.0;layer.timeOffset = 0.0;layer.beginTime = 0.0;CFTimeInterval timeSincePause = [layer convertTime:CACurrentMediaTime() fromLayer:nil] - pausedTime;layer.beginTime = timeSincePause;}
navigationBar根据滑动距离的渐变色实现
123456- (void)scrollViewDidScroll:(UIScrollView *)scrollView{CGFloat offsetToShow = 200.0;//滑动多少就完全显示CGFloat alpha = 1 - (offsetToShow - scrollView.contentOffset.y) / offsetToShow;[[self.navigationController.navigationBar subviews] objectAtIndex:0].alpha = alpha;}
UIWebView设置User-Agent
12345//设置NSDictionary *dic = @{@"UserAgent":@"your UserAgent"};[[NSUserDefaults standardUserDefaults] registerDefaults:dic];//获取NSString *agent = [self.WebView stringByEvaluatingJavaScriptFromString:@"navigator.userAgent"];
获取UIColor的RGBA值
123456UIColor *color = [UIColor colorWithRed:0.2 green:0.3 blue:0.9 alpha:1.0];const CGFloat *components = CGColorGetComponents(color.CGColor);NSLog(@"Red: %.1f", components[0]);NSLog(@"Green: %.1f", components[1]);NSLog(@"Blue: %.1f", components[2]);NSLog(@"Alpha: %.1f", components[3]);
判断两个日期是否在同一周
1234567891011121314151617- (BOOL)isSameDateWithDate:(NSDate *)date{//日期间隔大于七天之间返回NOif (fabs([self timeIntervalSinceDate:date]) >= 7 * 24 *3600){return NO;}NSCalendar *calender = [NSCalendar currentCalendar];calender.firstWeekday = 2;//设置每周第一天从周一开始//计算两个日期分别为这年第几周NSUInteger countSelf = [calender ordinalityOfUnit:NSCalendarUnitWeekday inUnit:NSCalendarUnitYear forDate:self];NSUInteger countDate = [calender ordinalityOfUnit:NSCalendarUnitWeekday inUnit:NSCalendarUnitYear forDate:date];//相等就在同一周,不相等就不在同一周return countSelf == countDate;}
字符串反转
12345678- (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;}
iOS 获取汉字的拼音
12345678910111213+ (NSString *)transform:(NSString *)chinese{//将NSString装换成NSMutableStringNSMutableString *pinyin = [chinese mutableCopy];//将汉字转换为拼音(带音标)CFStringTransform((__bridge CFMutableStringRef)pinyin, NULL, kCFStringTransformMandarinLatin, NO);NSLog(@"%@", pinyin);//去掉拼音的音标CFStringTransform((__bridge CFMutableStringRef)pinyin, NULL, kCFStringTransformStripCombiningMarks, NO);NSLog(@"%@", pinyin);//返回最近结果return pinyin;}
NSArray 快速求总和 最大值 最小值 和 平均值
123456NSArray *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);
计算文件(夹)大小
12345678910111213141516171819202122232425262728293031323334353637//文件大小- (long long)fileSizeAtPath:(NSString *)path{NSFileManager *fileManager = [NSFileManager defaultManager];if ([fileManager fileExistsAtPath:path]){long long size = [fileManager attributesOfItemAtPath:path error:nil].fileSize;return size;}return 0;}//文件夹大小- (long long)folderSizeAtPath:(NSString *)path{NSFileManager *fileManager = [NSFileManager defaultManager];long long folderSize = 0;if ([fileManager fileExistsAtPath:path]){NSArray *childerFiles = [fileManager subpathsAtPath:path];for (NSString *fileName in childerFiles){NSString *fileAbsolutePath = [path stringByAppendingPathComponent:fileName];if ([fileManager fileExistsAtPath:fileAbsolutePath]){long long size = [fileManager attributesOfItemAtPath:fileAbsolutePath error:nil].fileSize;folderSize += size;}}}return folderSize;}
图片上绘制文字
1234567891011121314151617181920212223242526272829- (UIImage *)imageWithTitle:(NSString *)title fontSize:(CGFloat)fontSize{//画布大小CGSize size=CGSizeMake(self.size.width,self.size.height);//创建一个基于位图的上下文UIGraphicsBeginImageContextWithOptions(size,NO,0.0);//opaque:NO scale:0.0[self drawAtPoint:CGPointMake(0.0,0.0)];//文字居中显示在画布上NSMutableParagraphStyle* paragraphStyle = [[NSParagraphStyle defaultParagraphStyle] mutableCopy];paragraphStyle.lineBreakMode = NSLineBreakByCharWrapping;paragraphStyle.alignment=NSTextAlignmentCenter;//文字居中//计算文字所占的size,文字居中显示在画布上CGSize sizeText=[title boundingRectWithSize:self.size options:NSStringDrawingUsesLineFragmentOriginattributes:@{NSFontAttributeName:[UIFont systemFontOfSize:fontSize]}context:nil].size;CGFloat width = self.size.width;CGFloat height = self.size.height;CGRect rect = CGRectMake((width-sizeText.width)/2, (height-sizeText.height)/2, sizeText.width, sizeText.height);//绘制文字[title drawInRect:rect withAttributes:@{ NSFontAttributeName:[UIFont systemFontOfSize:fontSize],NSForegroundColorAttributeName:[ UIColor whiteColor],NSParagraphStyleAttributeName:paragraphStyle}];//返回绘制的新图形UIImage *newImage= UIGraphicsGetImageFromCurrentImageContext();UIGraphicsEndImageContext();return newImage;}
开发技巧
上面说的是一些开发中会用到的一些实用的方法。下面具体说一下开发中可能会需要实用的一些技巧。
显示隐藏文件
1234567//显示defaults write com.apple.finder AppleShowAllFiles -bool truekillall Finder//隐藏defaults write com.apple.finder AppleShowAllFiles -bool falsekillall Finder
获取一个类的所有子类
123456789101112131415161718192021+ (NSArray *) allSubclasses{Class myClass = [self class];NSMutableArray *mySubclasses = [NSMutableArray array];unsigned int numOfClasses;Class *classes = objc_copyClassList(&numOfClasses;);for (unsigned int ci = 0; ci < numOfClasses; ci++){Class superClass = classes[ci];do{superClass = class_getSuperclass(superClass);} while (superClass && superClass != myClass);if (superClass){[mySubclasses addObject: classes[ci]];}}free(classes);return mySubclasses;}
监测IOS设备是否设置了代理,需要CFNetwork.framework
1234567891011121314151617NSDictionary *proxySettings = (__bridge NSDictionary *)(CFNetworkCopySystemProxySettings());NSArray *proxies = (__bridge NSArray *)(CFNetworkCopyProxiesForURL((__bridge CFURLRef _Nonnull)([NSURL URLWithString:@"http://www.baidu.com"]), (__bridge CFDictionaryRef _Nonnull)(proxySettings)));NSLog(@"\n%@",proxies);NSDictionary *settings = proxies[0];NSLog(@"%@",[settings objectForKey:(NSString *)kCFProxyHostNameKey]);NSLog(@"%@",[settings objectForKey:(NSString *)kCFProxyPortNumberKey]);NSLog(@"%@",[settings objectForKey:(NSString *)kCFProxyTypeKey]);if ([[settings objectForKey:(NSString *)kCFProxyTypeKey] isEqualToString:@"kCFProxyTypeNone"]){NSLog(@"没代理");}else{NSLog(@"设置了代理");}
让Xcode的控制台支持LLDB类型的打印
1234打开终端输入三条命令:touch ~/.lldbinitecho display @import UIKit >> ~/.lldbinitecho target stop-hook add -o \"target stop-hook disable\" >> ~/.lldbinit
CocoaPods pod install/pod update更新慢的问题
123pod install --verbose --no-repo-updatepod update --verbose --no-repo-update如果不加后面的参数,默认会升级CocoaPods的spec仓库,加一个参数可以省略这一步,然后速度就会提升不少
查找一个视图的所有子视图
12345678910111213- (NSMutableArray *)allSubViewsForView:(UIView *)view{NSMutableArray *array = [NSMutableArray arrayWithCapacity:0];for (UIView *subView in view.subviews){[array addObject:subView];if (subView.subviews.count > 0){[array addObjectsFromArray:[self allSubViewsForView:subView]];}}return array;}
获取私有属性和成员变量 #import
1234567891011121314151617181920212223242526272829303132333435//获取私有属性 比如设置UIDatePicker的字体颜色- (void)setTextColor{//获取所有的属性,去查看有没有对应的属性unsigned int count = 0;objc_property_t *propertys = class_copyPropertyList([UIDatePicker class], &count);for(int i = 0;i < count;i ++){//获得每一个属性objc_property_t property = propertys[i];//获得属性对应的nsstringNSString *propertyName = [NSString stringWithCString:property_getName(property) encoding:NSUTF8StringEncoding];//输出打印看对应的属性NSLog(@"propertyname = %@",propertyName);if ([propertyName isEqualToString:@"textColor"]){[datePicker setValue:[UIColor whiteColor] forKey:propertyName];}}}//获得成员变量 比如修改UIAlertAction的按钮字体颜色unsigned int count = 0;Ivar *ivars = class_copyIvarList([UIAlertAction class], &count);for(int i =0;i < count;i ++){Ivar ivar = ivars[i];NSString *ivarName = [NSString stringWithCString:ivar_getName(ivar) encoding:NSUTF8StringEncoding];NSLog(@"uialertion.ivarName = %@",ivarName);if ([ivarName isEqualToString:@"_titleTextColor"]){[alertOk setValue:[UIColor blueColor] forKey:@"titleTextColor"];[alertCancel setValue:[UIColor purpleColor] forKey:@"titleTextColor"];}}
获取手机安装的应用
12345678910Class c =NSClassFromString(@"LSApplicationWorkspace");id s = [(id)c performSelector:NSSelectorFromString(@"defaultWorkspace")];NSArray *array = [s performSelector:NSSelectorFromString(@"allInstalledApplications")];for (id item in array){NSLog(@"%@",[item performSelector:NSSelectorFromString(@"applicationIdentifier")]);//NSLog(@"%@",[item performSelector:NSSelectorFromString(@"bundleIdentifier")]);NSLog(@"%@",[item performSelector:NSSelectorFromString(@"bundleVersion")]);NSLog(@"%@",[item performSelector:NSSelectorFromString(@"shortVersionString")]);}
获取硬盘总容量与可用容量
12345NSFileManager *fileManager = [NSFileManager defaultManager];NSDictionary *attributes = [fileManager attributesOfFileSystemForPath:NSHomeDirectory() error:nil];NSLog(@"容量%.2fG",[attributes[NSFileSystemSize] doubleValue] / (powf(1024, 3)));NSLog(@"可用%.2fG",[attributes[NSFileSystemFreeSize] doubleValue] / powf(1024, 3));
获取WebView所有的图片地址
在网页加载完成时,通过js获取图片和添加点击的识别方式
1234567891011121314151617181920212223242526272829303132333435363738//UIWebView- (void)webViewDidFinishLoad:(UIWebView *)webView{//这里是js,主要目的实现对url的获取static NSString * const jsGetImages =@"function getImages(){\var objs = document.getElementsByTagName(\"img\");\var imgScr = '';\for(var i=0;i<objs.length;i++){\imgScr = imgScr + objs[i].src + '+';\};\return imgScr;\};";[webView stringByEvaluatingJavaScriptFromString:jsGetImages];//注入js方法NSString *urlResult = [webView stringByEvaluatingJavaScriptFromString:@"getImages()"];NSArray *urlArray = [NSMutableArray arrayWithArray:[urlResult componentsSeparatedByString:@"+"]];//urlResurlt 就是获取到得所有图片的url的拼接;mUrlArray就是所有Url的数组}//WKWebView- (void)webView:(WKWebView *)webView didFinishNavigation:(null_unspecified WKNavigation *)navigation{static NSString * const jsGetImages =@"function getImages(){\var objs = document.getElementsByTagName(\"img\");\var imgScr = '';\for(var i=0;i<objs.length;i++){\imgScr = imgScr + objs[i].src + '+';\};\return imgScr;\};";[webView evaluateJavaScript:jsGetImages completionHandler:nil];[webView evaluateJavaScript:@"getImages()" completionHandler:^(id _Nullable result, NSError * _Nullable error) {NSLog(@"%@",result);}];}iOS 开发中一些相关的路径
123456789101112131415模拟器的位置:/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
打印系统所有已注册的字体名称
123456789101112void enumerateFonts(){for(NSString *familyName in [UIFont familyNames]){NSLog(@"%@",familyName);NSArray *fontNames = [UIFont fontNamesForFamilyName:familyName];for(NSString *fontName in fontNames){NSLog(@"\t|- %@",fontName);}}}
本作品采用 署名-非商业性使用-相同方式共享 2.5 中国大陆 (CC BY-NC-SA 2.5)协议
进行许可,欢迎转载,但转载请注明来自SarielTang
,并保持转载后文章内容的完整。本人保留所有版权相关权利。
本文永久链接:http://sarieltang.github.io/2017/04/09/知识点小结/2017-04-09/index/