iOS小技巧总结
在这里总结一些iOS开发中的小技巧,能大大方便我们的开发,持续更新。
UITableView的Group样式下顶部空白处理
//分组列表头部空白处理UIView*view = [[UIViewalloc] initWithFrame:CGRectMake(0,0,0,0.1)];self.tableView.tableHeaderView= view;
UITableView的plain样式下,取消区头停滞效果
- (void)scrollViewDidScroll:(UIScrollView *)scrollView{ CGFloat sectionHeaderHeight = sectionHead.height;if(scrollView.contentOffset.y<=sectionHeaderHeight&&scrollView;.contentOffset.y>=0) { scrollView.contentInset = UIEdgeInsetsMake(-scrollView.contentOffset.y,0,0,0); }elseif(scrollView.contentOffset.y>=sectionHeaderHeight) { scrollView.contentInset = UIEdgeInsetsMake(-sectionHeaderHeight,0,0,0); }}
那个,其实,还是用Group样式吧哈哈。
获取某个view所在的控制器
- (UIViewController*)viewController{UIViewController*viewController =nil;UIResponder*next=self.nextResponder;while(next) {if([nextisKindOfClass:[UIViewControllerclass]]){ viewController = (UIViewController*)next;break; }next=next.nextResponder; }returnviewController;}
两种方法删除NSUserDefaults所有记录
//方法一NSString*appDomain = [[NSBundlemainBundle] bundleIdentifier];[[NSUserDefaultsstandardUserDefaults] removePersistentDomainForName:appDomain];//方法二- (void)resetDefaults{NSUserDefaults* defs = [NSUserDefaultsstandardUserDefaults];NSDictionary* dict = [defs dictionaryRepresentation];for(idkeyindict) { [defs removeObjectForKey:key]; } [defs synchronize];}
打印系统所有已注册的字体名称
#pragma mark - 打印系统所有已注册的字体名称voidenumerateFonts(){for(NSString*familyNamein[UIFontfamilyNames]) {NSLog(@"%@",familyName);NSArray*fontNames = [UIFontfontNamesForFamilyName:familyName];for(NSString*fontNameinfontNames) {NSLog(@"\t|- %@",fontName); } }}
获取图片某一点的颜色
- (UIColor*) getPixelColorAtLocation:(CGPoint)point inImage:(UIImage*)image{UIColor* color =nil;CGImageRefinImage = image.CGImage;CGContextRefcgctx = [selfcreateARGBBitmapContextFromImage:inImage];if(cgctx ==NULL) {returnnil;/* error */} size_t w =CGImageGetWidth(inImage); size_t h =CGImageGetHeight(inImage);CGRectrect = {{0,0},{w,h}};CGContextDrawImage(cgctx, rect, inImage);unsignedchar* data =CGBitmapContextGetData(cgctx);if(data !=NULL) {intoffset =4*((w*round(point.y))+round(point.x));intalpha = data[offset];intred = data[offset+1];intgreen = data[offset+2];intblue = data[offset+3]; color = [UIColorcolorWithRed:(red/255.0f) green:(green/255.0f) blue: (blue/255.0f) alpha:(alpha/255.0f)]; }CGContextRelease(cgctx);if(data) { free(data); }returncolor;}
字符串反转
第一种:- (NSString*)reverseWordsInString:(NSString*)str{NSMutableString*newString = [[NSMutableStringalloc] initWithCapacity:str.length];for(NSIntegeri = str.length-1; i >=0; i --) {unicharch = [str characterAtIndex:i]; [newString appendFormat:@"%c", ch]; }returnnewString;}//
第二种:- (NSString*)reverseWordsInString:(NSString*)str{NSMutableString*reverString = [NSMutableStringstringWithCapacity:str.length]; [str enumerateSubstringsInRange:NSMakeRange(0, str.length) options:NSStringEnumerationReverse|NSStringEnumerationByComposedCharacterSequencesusingBlock:^(NSString*substring,NSRangesubstringRange,NSRangeenclosingRange,BOOL*stop) { [reverString appendString:substring]; }];returnreverString;}
禁止锁屏,
默认情况下,当设备一段时间没有触控动作时,iOS会锁住屏幕。但有一些应用是不需要锁屏的,比如视频播放器。
[UIApplicationsharedApplication].idleTimerDisabled=YES;或[[UIApplicationsharedApplication] setIdleTimerDisabled:YES];
模态推出透明界面
UIViewController*vc = [[UIViewControlleralloc] init];UINavigationController*na = [[UINavigationControlleralloc] initWithRootViewController:vc];if([[[UIDevicecurrentDevice] systemVersion] floatValue] >=8.0){ na.modalPresentationStyle=UIModalPresentationOverCurrentContext;}else{self.modalPresentationStyle=UIModalPresentationCurrentContext;}[selfpresentViewController:na animated:YEScompletion:nil];
Xcode调试不显示内存占用
editSCheme 里面有个选项叫叫做enablezoombie Objects 取消选中
显示隐藏文件
//显示
defaults write com.apple.finderAppleShowAllFiles -booltruekillall Finder//隐藏defaults write com.apple.finderAppleShowAllFiles -boolfalsekillall Finder
字符串按多个符号分割
image.png
iOS跳转到App Store下载应用评分
[[UIApplication sharedApplication]openURL:[NSURL URLWithString:@"itms-apps://itunes.apple.com/WebObjects/MZStore.woa/wa/viewContentsUserReviews?type=Purple+Software&id=APPID"]];
iOS 获取汉字的拼音
+ (NSString*)transform:(NSString*)chinese{//将NSString装换成NSMutableStringNSMutableString*pinyin = [chinese mutableCopy];//将汉字转换为拼音(带音标)CFStringTransform((__bridgeCFMutableStringRef)pinyin,NULL, kCFStringTransformMandarinLatin,NO);NSLog(@"%@", pinyin);//去掉拼音的音标CFStringTransform((__bridgeCFMutableStringRef)pinyin,NULL, kCFStringTransformStripCombiningMarks,NO);NSLog(@"%@", pinyin);//返回最近结果returnpinyin; }
手动更改iOS状态栏的颜色
- (void)setStatusBarBackgroundColor:(UIColor*)color{UIView*statusBar = [[[UIApplicationsharedApplication] valueForKey:@"statusBarWindow"] valueForKey:@"statusBar"];if([statusBar respondsToSelector:@selector(setBackgroundColor:)]) { statusBar.backgroundColor= color; }}
判断当前ViewController是push还是present的方式显示的
NSArray*viewcontrollers=self.navigationController.viewControllers;if(viewcontrollers.count>1){if([viewcontrollers objectAtIndex:viewcontrollers.count-1] ==self) {//push方式[self.navigationControllerpopViewControllerAnimated:YES]; }}else{//present方式[selfdismissViewControllerAnimated:YEScompletion:nil];}
获取实际使用的LaunchImage图片
- (NSString*)getLaunchImageName{CGSizeviewSize =self.window.bounds.size;// 竖屏NSString*viewOrientation =@"Portrait";NSString*launchImageName =nil;NSArray* imagesDict = [[[NSBundlemainBundle] infoDictionary] valueForKey:@"UILaunchImages"];for(NSDictionary* dictinimagesDict) {CGSizeimageSize =CGSizeFromString(dict[@"UILaunchImageSize"]);if(CGSizeEqualToSize(imageSize, viewSize) && [viewOrientation isEqualToString:dict[@"UILaunchImageOrientation"]]) { launchImageName = dict[@"UILaunchImageName"]; } }returnlaunchImageName;}
iOS在当前屏幕获取第一响应
UIWindow* keyWindow = [[UIApplicationsharedApplication] keyWindow];UIView* firstResponder = [keyWindow performSelector:@selector(firstResponder)];
判断对象是否遵循了某协议
if([self.selectedControllerconformsToProtocol:@protocol(RefreshPtotocol)]){ [self.selectedControllerperformSelector:@selector(onTriggerRefresh)];}
判断view是不是指定视图的子视图
BOOLisView = [textView isDescendantOfView:self.view];
NSArray 快速求总和 最大值 最小值 和 平均值
NSArray*array = [NSArrayarrayWithObjects:@"2.0",@"2.3",@"3.0",@"4.0",@"10",nil];CGFloatsum = [[array valueForKeyPath:@"@sum.floatValue"] floatValue];CGFloatavg = [[array valueForKeyPath:@"@avg.floatValue"] floatValue];CGFloatmax =[[array valueForKeyPath:@"@max.floatValue"] floatValue];CGFloatmin =[[array valueForKeyPath:@"@min.floatValue"] floatValue];NSLog(@"%f\n%f\n%f\n%f",sum,avg,max,min);
修改UITextField中Placeholder的文字颜色
[textField setValue:[UIColor redColor]forKeyPath:@"_placeholderLabel.textColor"];
关于NSDateFormatter的格式
G: 公元时代,例如AD公元yy: 年的后2位yyyy: 完整年MM: 月,显示为1-12MMM: 月,显示为英文月份简写,如 JanMMMM: 月,显示为英文月份全称,如 Janualydd: 日,2位数表示,如02d: 日,1-2位显示,如2EEE: 简写星期几,如SunEEEE: 全写星期几,如Sundayaa: 上下午,AM/PMH: 时,24小时制,0-23K:时,12小时制,0-11m: 分,1-2位mm: 分,2位s: 秒,1-2位ss: 秒,2位S: 毫秒
获取一个类的所有子类
+ (NSArray*) allSubclasses{ Class myClass = [selfclass];NSMutableArray*mySubclasses = [NSMutableArrayarray];unsignedintnumOfClasses; Class *classes = objc_copyClassList(&numOfClasses;);for(unsignedintci =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);returnmySubclasses;}
监测IOS设备是否设置了代理,需要CFNetwork.framework
NSDictionary*proxySettings = (__bridgeNSDictionary*)(CFNetworkCopySystemProxySettings());NSArray*proxies = (__bridgeNSArray*)(CFNetworkCopyProxiesForURL((__bridgeCFURLRef_Nonnull)([NSURLURLWithString:@"http://www.baidu.com"]), (__bridgeCFDictionaryRef_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(@"设置了代理");}
阿拉伯数字转中文格式
+(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 = [NSDictionarydictionaryWithObjects:chinese_numerals forKeys:arabic_numerals];NSMutableArray*sums = [NSMutableArrayarray];for(inti =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);returnchinese;}
Base64编码与NSString对象或NSData对象的转换
// Create NSData objectNSData*nsdata = [@"iOS Developer Tips encoded in Base64"dataUsingEncoding:NSUTF8StringEncoding];// Get NSString from NSData object in Base64NSString*base64Encoded = [nsdata base64EncodedStringWithOptions:0];// Print the Base64 encoded stringNSLog(@"Encoded: %@", base64Encoded);// Let's go the other way...// NSData from the Base64 encoded strNSData*nsdataFromBase64String = [[NSDataalloc] initWithBase64EncodedString:base64Encoded options:0];// Decoded NSString from the NSDataNSString*base64Decoded = [[NSStringalloc] initWithData:nsdataFromBase64String encoding:NSUTF8StringEncoding];NSLog(@"Decoded: %@", base64Decoded);
取消UICollectionView的隐式动画
UICollectionView在reloadItems的时候,默认会附加一个隐式的fade动画,有时候很讨厌,尤其是当你的cell是复合cell的情况下(比如cell使用到了UIStackView)。
下面几种方法都可以帮你去除这些动画
//方法一[UIViewperformWithoutAnimation:^{ [collectionView reloadItemsAtIndexPaths:@[[NSIndexPathindexPathForItem:index inSection:0]]];}];//方法二[UIViewanimateWithDuration:0animations:^{ [collectionView performBatchUpdates:^{ [collectionView reloadItemsAtIndexPaths:@[[NSIndexPathindexPathForItem:index inSection:0]]]; } completion:nil];}];//方法三[UIViewsetAnimationsEnabled:NO];[self.trackPanelperformBatchUpdates:^{ [collectionView reloadItemsAtIndexPaths:@[[NSIndexPathindexPathForItem:index inSection:0]]];} completion:^(BOOLfinished) { [UIViewsetAnimationsEnabled:YES];}];
让Xcode的控制台支持LLDB类型的打印
打开终端输入三条命令:touch ~/.lldbinitechodisplay @import UIKit >> ~/.lldbinitechotarget stop-hook add -o \"target stop-hook disable\" >> ~/.lldbinit
CocoaPods pod install/pod update更新慢的问题
podinstall--verbose --no-repo-updatepodupdate--verbose --no-repo-update如果不加后面的参数,默认会升级CocoaPods的spec仓库,加一个参数可以省略这一步,然后速度就会提升不少
UIImage 占用内存大小
UIImage*image = [UIImageimageNamed:@"aa"];NSUIntegersize =CGImageGetHeight(image.CGImage) *CGImageGetBytesPerRow(image.CGImage);
GCD timer定时器
dispatch_queue_tqueue= dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT,0);dispatch_source_ttimer = 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_source_cancel(timer); dispatch_async(dispatch_get_main_queue(), ^{ });});dispatch_resume(timer);
图片上绘制文字 写一个UIImage的category
- (UIImage*)imageWithTitle:(NSString*)title fontSize:(CGFloat)fontSize{//画布大小CGSizesize=CGSizeMake(self.size.width,self.size.height);//创建一个基于位图的上下文UIGraphicsBeginImageContextWithOptions(size,NO,0.0);//opaque:NO scale:0.0[selfdrawAtPoint:CGPointMake(0.0,0.0)];//文字居中显示在画布上NSMutableParagraphStyle* paragraphStyle = [[NSParagraphStyledefaultParagraphStyle] mutableCopy]; paragraphStyle.lineBreakMode=NSLineBreakByCharWrapping; paragraphStyle.alignment=NSTextAlignmentCenter;//文字居中//计算文字所占的size,文字居中显示在画布上CGSizesizeText=[title boundingRectWithSize:self.sizeoptions:NSStringDrawingUsesLineFragmentOriginattributes:@{NSFontAttributeName:[UIFontsystemFontOfSize:fontSize]}context:nil].size;CGFloatwidth =self.size.width;CGFloatheight =self.size.height;CGRectrect =CGRectMake((width-sizeText.width)/2, (height-sizeText.height)/2, sizeText.width, sizeText.height);//绘制文字[title drawInRect:rect withAttributes:@{NSFontAttributeName:[UIFontsystemFontOfSize:fontSize],NSForegroundColorAttributeName:[UIColorwhiteColor],NSParagraphStyleAttributeName:paragraphStyle}];//返回绘制的新图形UIImage*newImage=UIGraphicsGetImageFromCurrentImageContext();UIGraphicsEndImageContext();returnnewImage;}
查找一个视图的所有子视图
- (NSMutableArray*)allSubViewsForView:(UIView*)view{NSMutableArray*array = [NSMutableArrayarrayWithCapacity:0];for(UIView*subViewinview.subviews) { [array addObject:subView];if(subView.subviews.count>0) { [array addObjectsFromArray:[selfallSubViewsForView:subView]]; } }returnarray;}
计算文件大小
//文件大小- (longlong)fileSizeAtPath:(NSString*)path{NSFileManager*fileManager = [NSFileManagerdefaultManager];if([fileManager fileExistsAtPath:path]) {longlongsize = [fileManager attributesOfItemAtPath:path error:nil].fileSize;returnsize; }return0;}//文件夹大小- (longlong)folderSizeAtPath:(NSString*)path{NSFileManager*fileManager = [NSFileManagerdefaultManager];longlongfolderSize =0;if([fileManager fileExistsAtPath:path]) {NSArray*childerFiles = [fileManager subpathsAtPath:path];for(NSString*fileNameinchilderFiles) {NSString*fileAbsolutePath = [path stringByAppendingPathComponent:fileName];if([fileManager fileExistsAtPath:fileAbsolutePath]) {longlongsize = [fileManager attributesOfItemAtPath:fileAbsolutePath error:nil].fileSize; folderSize += size; } } }returnfolderSize;}
UIView设置部分圆角
你是不是也遇到过这样的问题,一个button或者label,只要右边的两个角圆角,或者只要一个圆角。该怎么办呢。这就需要图层蒙版来帮助我们了
CGRectrect = view.bounds;CGSizeradio =CGSizeMake(30,30);//圆角尺寸UIRectCornercorner =UIRectCornerTopLeft|UIRectCornerTopRight;//这只圆角位置UIBezierPath*path = [UIBezierPathbezierPathWithRoundedRect:rect byRoundingCorners:corner cornerRadii:radio];CAShapeLayer*masklayer = [[CAShapeLayeralloc]init];//创建shapelayermasklayer.frame= view.bounds;masklayer.path= path.CGPath;//设置路径view.layer.mask= masklayer;
取上整与取下整
floor(x),有时候也写做Floor(x),其功能是“下取整”,即取不大于x的最大整数 例如:x=3.14,floor(x)=3y=9.99999,floor(y)=9与floor函数对应的是ceil函数,即上取整函数。ceil函数的作用是求不小于给定实数的最小整数。ceil(2)=ceil(1.2)=cei(1.5)=2.00floor函数与ceil函数的返回值均为double型
计算字符串字符长度,一个汉字算两个字符
//方法一:- (int)convertToInt:(NSString*)strtemp{intstrlength =0;char* p = (char*)[strtemp cStringUsingEncoding:NSUnicodeStringEncoding];for(inti=0; i<[strtemp lengthOfBytesUsingEncoding:NSUnicodeStringEncoding] ;i++) {if(*p) { p++; strlength++; }else{ p++; } }returnstrlength;}//方法二:-(NSUInteger) unicodeLengthOfString: (NSString*) text{NSUIntegerasciiLength =0;for(NSUIntegeri =0; i < text.length; i++) {unicharuc = [text characterAtIndex: i]; asciiLength += isascii(uc) ?1:2; }returnasciiLength;}
给UIView设置图片
UIImage*image = [UIImageimageNamed:@"image"];self.MYView.layer.contents= (__bridgeid_Nullable)(image.CGImage);self.MYView.layer.contentsRect=CGRectMake(0,0,0.5,0.5);
防止scrollView手势覆盖侧滑手势
[scrollView.panGestureRecognizerrequireGestureRecognizerToFail:self.navigationController.interactivePopGestureRecognizer];
去掉导航栏返回的back标题
[[UIBarButtonItemappearance]setBackButtonTitlePositionAdjustment:UIOffsetMake(0, -60)forBarMetrics:UIBarMetricsDefault];
字符串中是否含有中文
+ (BOOL)checkIsChinese:(NSString *)string{for(inti=0; i
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(@"请求完成");});
UITextField每四位加一个空格,实现代理
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{// 四位加一个空格if([stringisEqualToString:@""]) {// 删除字符if((textField.text.length -2) %5==0) { textField.text = [textField.text substringToIndex:textField.text.length -1]; }returnYES; }else{if(textField.text.length %5==0) { textField.text = [NSString stringWithFormat:@"%@ ", textField.text]; } }returnYES;}
获取私有属性和成员变量 #import
//获取私有属性 比如设置UIDatePicker的字体颜色- (void)setTextColor{//获取所有的属性,去查看有没有对应的属性unsignedintcount =0; objc_property_t *propertys = class_copyPropertyList([UIDatePickerclass], &count);for(inti =0;i < count;i ++) {//获得每一个属性objc_property_t property = propertys[i];//获得属性对应的nsstringNSString*propertyName = [NSStringstringWithCString:property_getName(property) encoding:NSUTF8StringEncoding];//输出打印看对应的属性NSLog(@"propertyname = %@",propertyName);if([propertyName isEqualToString:@"textColor"]) { [datePicker setValue:[UIColorwhiteColor] forKey:propertyName]; } }}
//获得成员变量 比如修改UIAlertAction的按钮字体颜色unsignedintcount =0; Ivar *ivars = class_copyIvarList([UIAlertActionclass], &count);for(inti =0;i < count;i ++) { Ivar ivar = ivars[i];NSString*ivarName = [NSStringstringWithCString:ivar_getName(ivar) encoding:NSUTF8StringEncoding];NSLog(@"uialertion.ivarName = %@",ivarName);if([ivarName isEqualToString:@"_titleTextColor"]) { [alertOk setValue:[UIColorblueColor] forKey:@"titleTextColor"]; [alertCancel setValue:[UIColorpurpleColor] forKey:@"titleTextColor"]; } }
获取手机安装的应用
Class c =NSClassFromString(@"LSApplicationWorkspace");ids = [(id)c performSelector:NSSelectorFromString(@"defaultWorkspace")];NSArray*array = [s performSelector:NSSelectorFromString(@"allInstalledApplications")];for(iditeminarray){NSLog(@"%@",[item performSelector:NSSelectorFromString(@"applicationIdentifier")]);//NSLog(@"%@",[item performSelector:NSSelectorFromString(@"bundleIdentifier")]);NSLog(@"%@",[item performSelector:NSSelectorFromString(@"bundleVersion")]);NSLog(@"%@",[item performSelector:NSSelectorFromString(@"shortVersionString")]);}
判断两个日期是否在同一周 写在NSDate的category里面
- (BOOL)isSameDateWithDate:(NSDate*)date{//日期间隔大于七天之间返回NOif(fabs([selftimeIntervalSinceDate:date]) >=7*24*3600) {returnNO; }NSCalendar*calender = [NSCalendarcurrentCalendar]; calender.firstWeekday=2;//设置每周第一天从周一开始//计算两个日期分别为这年第几周NSUIntegercountSelf = [calender ordinalityOfUnit:NSCalendarUnitWeekdayinUnit:NSCalendarUnitYearforDate:self];NSUIntegercountDate = [calender ordinalityOfUnit:NSCalendarUnitWeekdayinUnit:NSCalendarUnitYearforDate:date];//相等就在同一周,不相等就不在同一周returncountSelf == countDate;}
应用内打开系统设置界面
//iOS8之后[[UIApplicationsharedApplication] openURL:[NSURLURLWithString:UIApplicationOpenSettingsURLString]];//如果App没有添加权限,显示的是设定界面。如果App有添加权限(例如通知),显示的是App的设定界面。
//iOS8之前//先添加一个url type如下图,在代码中调用如下代码,即可跳转到设置页面的对应项[[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"prefs:root=WIFI"]];可选值如下:About — prefs:root=General&path=AboutAccessibility — prefs:root=General&path=ACCESSIBILITYAirplane Mode On — prefs:root=AIRPLANE_MODEAuto-Lock— prefs:root=General&path=AUTOLOCKBrightness — prefs:root=BrightnessBluetooth — prefs:root=General&path=BluetoothDate&Time— prefs:root=General&path=DATE_AND_TIMEFaceTime — prefs:root=FACETIMEGeneral— prefs:root=GeneralKeyboard — prefs:root=General&path=KeyboardiCloud — prefs:root=CASTLEiCloudStorage&Backup— prefs:root=CASTLE&path=STORAGE_AND_BACKUPInternational — prefs:root=General&path=INTERNATIONALLocation Services — prefs:root=LOCATION_SERVICESMusic — prefs:root=MUSICMusic Equalizer — prefs:root=MUSIC&path=EQMusic VolumeLimit— prefs:root=MUSIC&path=VolumeLimitNetwork — prefs:root=General&path=NetworkNike + iPod — prefs:root=NIKE_PLUS_IPODNotes — prefs:root=NOTESNotification — prefs:root=NOTIFICATI*****_IDPhone — prefs:root=PhonePhotos — prefs:root=PhotosProfile — prefs:root=General&path=ManagedConfigurationListReset— prefs:root=General&path=ResetSafari — prefs:root=SafariSiri — prefs:root=General&path=AssistantSounds — prefs:root=SoundsSoftwareUpdate— prefs:root=General&path=SOFTWARE_UPDATE_LINKStore— prefs:root=STORETwitter — prefs:root=TWITTERUsage— prefs:root=General&path=USAGEVPN — prefs:root=General&path=Network/VPNWallpaper — prefs:root=WallpaperWi-Fi — prefs:root=WIFI
Image.png
屏蔽触发事件,2秒后取消屏蔽
[[UIApplicationsharedApplication] beginIgnoringInteractionEvents];dispatch_after(dispatch_time(DISPATCH_TIME_NOW,(int64_t)(2* NSEC_PER_SEC)), dispatch_get_main_queue(), ^{[[UIApplicationsharedApplication] endIgnoringInteractionEvents]});
动画暂停再开始
-(void)pauseLayer:(CALayer*)layer{CFTimeIntervalpausedTime = [layer convertTime:CACurrentMediaTime() fromLayer:nil]; layer.speed=0.0; layer.timeOffset= pausedTime;}-(void)resumeLayer:(CALayer*)layer{CFTimeIntervalpausedTime = [layer timeOffset]; layer.speed=1.0; layer.timeOffset=0.0; layer.beginTime=0.0;CFTimeIntervaltimeSincePause = [layer convertTime:CACurrentMediaTime() fromLayer:nil] - pausedTime; layer.beginTime= timeSincePause;}
fillRule原理
Image.png
iOS中数字的格式化
//通过NSNumberFormatter,同样可以设置NSNumber输出的格式。例如如下代码:NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];formatter.numberStyle = NSNumberFormatterDecimalStyle;NSString *string= [formatter stringFromNumber:[NSNumber numberWithInt:123456789]];NSLog(@"Formatted number string:%@",string);//输出结果为:[1223:403] Formatted number string:123,456,789//其中NSNumberFormatter类有个属性numberStyle,它是一个枚举型,设置不同的值可以输出不同的数字格式。该枚举包括:typedefNS_ENUM(NSUInteger, NSNumberFormatterStyle){ NSNumberFormatterNoStyle = kCFNumberFormatterNoStyle, NSNumberFormatterDecimalStyle = kCFNumberFormatterDecimalStyle, NSNumberFormatterCurrencyStyle = kCFNumberFormatterCurrencyStyle, NSNumberFormatterPercentStyle = kCFNumberFormatterPercentStyle, NSNumberFormatterScientificStyle = kCFNumberFormatterScientificStyle, NSNumberFormatterSpellOutStyle = kCFNumberFormatterSpellOutStyle};//各个枚举对应输出数字格式的效果如下:其中第三项和最后一项的输出会根据系统设置的语言区域的不同而不同。[1243:403] Formatted numberstring:123456789[1243:403] Formatted numberstring:123,456,789[1243:403] Formatted numberstring:¥123,456,789.00[1243:403] Formatted numberstring:-539,222,988%[1243:403] Formatted numberstring:1.23456789E8[1243:403] Formatted numberstring:一亿二千三百四十五万六千七百八十九
如何获取WebView所有的图片地址,
在网页加载完成时,通过js获取图片和添加点击的识别方式
//UIWebView- (void)webViewDidFinishLoad:(UIWebView*)webView{//这里是js,主要目的实现对url的获取staticNSString*constjsGetImages =@"function getImages(){\
var objs = document.getElementsByTagName(\"img\");\
var imgScr = '';\
for(var i=0;i
imgScr = imgScr + objs[i].src + '+';\
};\
return imgScr;\
};"; [webView stringByEvaluatingJavaScriptFromString:jsGetImages];//注入js方法NSString*urlResult = [webView stringByEvaluatingJavaScriptFromString:@"getImages()"];NSArray*urlArray = [NSMutableArrayarrayWithArray:[urlResult componentsSeparatedByString:@"+"]];//urlResurlt 就是获取到得所有图片的url的拼接;mUrlArray就是所有Url的数组}
//WKWebView- (void)webView:(WKWebView *)webView didFinishNavigation:(null_unspecified WKNavigation *)navigation{staticNSString*constjsGetImages =@"function getImages(){\
var objs = document.getElementsByTagName(\"img\");\
var imgScr = '';\
for(var i=0;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); }];}
获取到webview的高度
CGFloatheight = [[self.webViewstringByEvaluatingJavaScriptFromString:@"document.body.offsetHeight"] floatValue];
navigationBar变为纯透明
//第一种方法//导航栏纯透明[self.navigationBarsetBackgroundImage:[UIImagenew] forBarMetrics:UIBarMetricsDefault];//去掉导航栏底部的黑线self.navigationBar.shadowImage= [UIImagenew];//第二种方法[[self.navigationBarsubviews] objectAtIndex:0].alpha=0;
tabBar同理
[self.tabBarsetBackgroundImage:[UIImagenew]];self.tabBar.shadowImage= [UIImagenew];
navigationBar根据滑动距离的渐变色实现
//第一种- (void)scrollViewDidScroll:(UIScrollView*)scrollView{CGFloatoffsetToShow =200.0;//滑动多少就完全显示CGFloatalpha =1- (offsetToShow - scrollView.contentOffset.y) / offsetToShow; [[self.navigationController.navigationBarsubviews] objectAtIndex:0].alpha= alpha;}
//第二种- (void)scrollViewDidScroll:(UIScrollView*)scrollView{CGFloatoffsetToShow =200.0;CGFloatalpha =1- (offsetToShow - scrollView.contentOffset.y) / offsetToShow; [self.navigationController.navigationBarsetShadowImage:[UIImagenew]]; [self.navigationController.navigationBarsetBackgroundImage:[selfimageWithColor:[[UIColororangeColor]colorWithAlphaComponent:alpha]] forBarMetrics:UIBarMetricsDefault];}//生成一张纯色的图片- (UIImage*)imageWithColor:(UIColor*)color{CGRectrect =CGRectMake(0.0f,0.0f,1.0f,1.0f);UIGraphicsBeginImageContext(rect.size);CGContextRefcontext =UIGraphicsGetCurrentContext();CGContextSetFillColorWithColor(context, [colorCGColor]);CGContextFillRect(context, rect);UIImage*theImage =UIGraphicsGetImageFromCurrentImageContext();UIGraphicsEndImageContext();returntheImage;}
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
navigationItem的BarButtonItem如何紧靠屏幕右边界或者左边界?
一般情况下,右边的item会和屏幕右侧保持一段距离:
image.png
下面是通过添加一个负值宽度的固定间距的item来解决,也可以改变宽度实现不同的间隔:
UIImage*img = [[UIImageimageNamed:@"icon_cog"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];//宽度为负数的固定间距的系统itemUIBarButtonItem*rightNegativeSpacer = [[UIBarButtonItemalloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpacetarget:nilaction:nil];[rightNegativeSpacer setWidth:-15];UIBarButtonItem*rightBtnItem1 = [[UIBarButtonItemalloc]initWithImage:img style:UIBarButtonItemStylePlaintarget:selfaction:@selector(rightButtonItemClicked:)];UIBarButtonItem*rightBtnItem2 = [[UIBarButtonItemalloc]initWithImage:img style:UIBarButtonItemStylePlaintarget:selfaction:@selector(rightButtonItemClicked:)];self.navigationItem.rightBarButtonItems= @[rightNegativeSpacer,rightBtnItem1,rightBtnItem2];
image.png
NSString进行URL编码和解码
NSString *string=@"http://abc.com?aaa=你好&bbb=tttee";//编码 打印:http://abc.com?aaa=%E4%BD%A0%E5%A5%BD&bbb=ttteestring= [stringstringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];//解码 打印:http://abc.com?aaa=你好&bbb=ttteestring= [stringstringByRemovingPercentEncoding];
UIWebView设置User-Agent。
//设置NSDictionary*dic = @{@"UserAgent":@"your UserAgent"};[[NSUserDefaultsstandardUserDefaults] registerDefaults:dic];//获取NSString*agent = [self.WebViewstringByEvaluatingJavaScriptFromString:@"navigator.userAgent"];
获取硬盘总容量与可用容量:
NSFileManager*fileManager = [NSFileManagerdefaultManager];NSDictionary*attributes = [fileManager attributesOfFileSystemForPath:NSHomeDirectory() error:nil];NSLog(@"容量%.2fG",[attributes[NSFileSystemSize] doubleValue] / (powf(1024,3)));NSLog(@"可用%.2fG",[attributes[NSFileSystemFreeSize] doubleValue] / powf(1024,3));
获取UIColor的RGBA值
UIColor*color = [UIColorcolorWithRed:0.2green:0.3blue:0.9alpha:1.0];constCGFloat*components =CGColorGetComponents(color.CGColor);NSLog(@"Red: %.1f", components[0]);NSLog(@"Green: %.1f", components[1]);NSLog(@"Blue: %.1f", components[2]);NSLog(@"Alpha: %.1f", components[3]);
修改textField的placeholder的字体颜色、大小
[self.textField setValue:[UIColor redColor]forKeyPath:@"_placeholderLabel.textColor"];[self.textField setValue:[UIFont boldSystemFontOfSize:16]forKeyPath:@"_placeholderLabel.font"];
AFN移除JSON中的NSNull
AFJSONResponseSerializer *response = [AFJSONResponseSerializer serializer];response.removesKeysWithNullValues=YES;
ceil()和floor()
ceil()功 能:返回大于或者等于指定表达式的最小整数
floor()功 能:返回小于或者等于指定表达式的最大整数
UIWebView里面的图片自适应屏幕
在webView加载完的代理方法里面这样写:
- (void)webViewDidFinishLoad:(UIWebView*)webView{NSString*js =@"function imgAutoFit() { \
var imgs = document.getElementsByTagName('img'); \
for (var i = 0; i < imgs.length; ++i) { \
var img = imgs[i]; \
img.style.maxWidth = %f; \
} \
}"; js = [NSStringstringWithFormat:js, [UIScreenmainScreen].bounds.size.width-20]; [webView stringByEvaluatingJavaScriptFromString:js]; [webView stringByEvaluatingJavaScriptFromString:@"imgAutoFit()"];}
文/iOS_小松哥(简书作者)
原文链接:http://www.jianshu.com/p/4523eafb4cd4#
著作权归作者所有,转载请联系作者获得授权,并标注“简书作者”。