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);}? ? else if(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;? ?

}

return viewController;

}

兩種方法刪除NSUserDefaults所有記錄

//方法一NSString*appDomain = [[NSBundlemainBundle] bundleIdentifier];[[NSUserDefaultsstandardUserDefaults] removePersistentDomainForName:appDomain];

//方法二- (void)resetDefaults{NSUserDefaults* defs = [NSUserDefaultsstandardUserDefaults];

NSDictionary* dict = [defs dictionaryRepresentation];

for(id key in dict) ?

{ ? ?

? [defs removeObjectForKey:key]; ??

}?

? [defs synchronize];}

打印系統所有已注冊的字體名稱

#pragma mark - 打印系統所有已注冊的字體名稱

void enumerateFonts() {

for(NSString*family Namein[UIFont familyNames])? {

NSLog(@"%@",familyName);

NSArray*fontNames = [UIFont fontNamesForFamilyName:familyName];

for(NSString*fontNameinfontNames)? ?

? {

NSLog(@"\t|- %@",fontName);? ? ?

}?

}

}

取圖片某一像素點的顏色 在UIImage的分類中

- (UIColor*)colorAtPixel:(CGPoint)point{

if(!CGRectContainsPoint(CGRectMake(0.0f,0.0f,self.size.width,self.size.height), point))? ?

{

return nil;? ?

}

CGColor SpaceRefcolorSpace =CGColorSpaceCreateDeviceRGB();

int bytesPerPixel =4;

int bytesPerRow = bytesPerPixel *1;

NSUInteger bitsPerComponent =8;

unsignedchar pixelData[4] = {0,0,0,0};

CGContextRef context =CGBitmapContextCreate(pixelData,1,1,? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? bitsPerComponent,bytesPerRow,colorSpace,kCGImageAlphaPremultipliedLast | kCGBitmapByteOrder32Big);

CGColorSpaceRelease(colorSpace);

CGContextSetBlendMode(context, kCGBlendModeCopy);

CGContextTranslateCTM(context, -point.x, point.y -self.size.height);

CGContextDrawImage(context,CGRectMake(0.0f,0.0f,self.size.width,self.size.height),self.CGImage);

CGContextRelease(context);

CGFloat red? = (CGFloat)pixelData[0] /255.0f;

CGFloat green = (CGFloat)pixelData[1] /255.0f;

CGFloat blue? = (CGFloat)pixelData[2] /255.0f;

CGFloat alpha = (CGFloat)pixelData[3] /255.0f;

return [UIColor colorWithRed:red green:green blue:blue alpha:alpha];

}

字符串反轉

第一種:- (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];? ? ? ?

}

return newString;

}

//第二種:- (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];? ? ? ? ? ? ? ? ? ? ? ? ? ? ?

}];

return reverString;

}

禁止鎖屏,

默認情況下,當設備一段時間沒有觸控動作時,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;

}

[self presentViewController:na animated:YEScompletion:nil];

Xcode調試不顯示內存占用

editSCheme? 里面有個選項叫叫做enablezoombie Objects? 取消選中

顯示隱藏文件

//顯示defaults write com.apple.finderAppleShowAllFiles -bool truekillall Finder

//隱藏defaults write com.apple.finderAppleShowAllFiles -bool falsekillall 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裝換成NSMutableString

NSMutableString*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 = [[[UIApplication sharedApplication]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.navigationController popViewControllerAnimated: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.selectedController performSelector:@selector(onTriggerRefresh)];}

判斷view是不是指定視圖的子視圖

BOOL isView= [textView isDescendantOfView:self.view];

NSArray 快速求總和 最大值 最小值 和 平均值

NSArray *array= [NSArray arrayWithObjects:@"2.0", @"2.3", @"3.0", @"4.0", @"10", nil];CGFloat sum = [[arrayvalueForKeyPath:@"@sum.floatValue"] floatValue];CGFloat avg = [[arrayvalueForKeyPath:@"@avg.floatValue"] floatValue];CGFloatmax=[[arrayvalueForKeyPath:@"@max.floatValue"] floatValue];CGFloatmin=[[arrayvalueForKeyPath:@"@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_numeralsforKeys:arabic_numerals];NSMutableArray *sums = [NSMutableArray array];for (int i =0; i < str.length; i ++) {NSString *substr= [strsubstringWithRange:NSMakeRange(i,1)];NSString *a = [dictionaryobjectForKey:substr];NSString *b=digits[str.length-i-1];NSString *sum = [a stringByAppendingString:b];if ([a isEqualToString:chinese_numerals[9]])? ? ? ? {? ? ? ? ? ? if([bisEqualToString:digits[4]]||[bisEqualToString:digits[8]]){? ? ? ? ? ? ? ? sum =b;if ([[sums lastObject] isEqualToString:chinese_numerals[9]])? ? ? ? ? ? ? ? {? ? ? ? ? ? ? ? ? ? [sums removeLastObject];}? ? ? ? ? ? }else? ? ? ? ? ? {? ? ? ? ? ? ? ? sum = chinese_numerals[9];}? ? ? ? ? ? if ([[sums lastObject] isEqualToString:sum])? ? ? ? ? ? {? ? ? ? ? ? ? ? continue;}? ? ? ? }? ? ? ? [sumsaddObject:sum];}? ? NSString *sumStr = [sums componentsJoinedByString:@""];NSString *chinese = [sumStrsubstringToIndex:sumStr.length-1];NSLog(@"%@",str);NSLog(@"%@",chinese);return chinese;}

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:^{? ? [collectionViewreloadItemsAtIndexPaths:@[[NSIndexPathindexPathForItem:indexinSection:0]]];}];//方法二[UIViewanimateWithDuration:0animations:^{? ? [collectionViewperformBatchUpdates:^{? ? ? ? [collectionViewreloadItemsAtIndexPaths:@[[NSIndexPathindexPathForItem:indexinSection:0]]];? ? }completion:nil];}];//方法三[UIViewsetAnimationsEnabled:NO];[self.trackPanelperformBatchUpdates:^{? ? [collectionViewreloadItemsAtIndexPaths:@[[NSIndexPathindexPathForItem:indexinSection:0]]];}completion:^(BOOL finished) {? ? [UIViewsetAnimationsEnabled:YES];}];

讓Xcode的控制臺支持LLDB類型的打印

打開終端輸入三條命令:touch ~/.lldbinitechodisplay@import UIKit >> ~/.lldbinitechotargetstop-hookadd-o\"target stop-hook disable\">> ~/.lldbinit

CocoaPods pod install/pod update更新慢的問題

pod install --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_t queue = 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.size options: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= [NSMutableArray arrayWithCapacity:0];for(UIView *subViewinview.subviews)? ? {? ? ? ? [arrayaddObject:subView];if(subView.subviews.count >0)? ? ? ? {? ? ? ? ? ? [arrayaddObjectsFromArray:[self allSubViewsForView:subView]];? ? ? ? }? ? }returnarray;}

計算文件大小

//文件大小- (longlong)fileSizeAtPath:(NSString *)path{? ? NSFileManager *fileManager = [NSFileManager defaultManager];if([fileManagerfileExistsAtPath:path])? ? {longlongsize = [fileManagerattributesOfItemAtPath:patherror:nil].fileSize;returnsize;? ? }return0;}//文件夾大小- (longlong)folderSizeAtPath:(NSString *)path{? ? NSFileManager *fileManager = [NSFileManager defaultManager];longlongfolderSize =0;if([fileManagerfileExistsAtPath:path])? ? {? ? ? ? NSArray *childerFiles = [fileManagersubpathsAtPath:path];for(NSString *fileNameinchilderFiles)? ? ? ? {? ? ? ? ? ? NSString *fileAbsolutePath = [pathstringByAppendingPathComponent:fileName];if([fileManagerfileExistsAtPath:fileAbsolutePath])? ? ? ? ? ? {longlongsize = [fileManagerattributesOfItemAtPath:fileAbsolutePatherror: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.textsubstringToIndex: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之后[[UIApplication sharedApplication] openURL:[NSURL URLWithString: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;CFTimeInterval timeSincePause = [layer convertTime:CACurrentMediaTime() fromLayer:nil] -pausedTime;layer.beginTime= timeSincePause;}

fillRule原理

Image.png

iOS中數字的格式化

//通過NSNumberFormatter,同樣可以設置NSNumber輸出的格式。例如如下代碼:NSNumberFormatter*formatter = [[NSNumberFormatteralloc] init];formatter.numberStyle =NSNumberFormatterDecimalStyle;NSString*string = [formatter stringFromNumber:[NSNumbernumberWithInt: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 number string:123456789[1243:403] Formatted number string:123,456,789[1243:403] Formatted number string:¥123,456,789.00[1243:403] Formatted number string:-539,222,988%[1243:403] Formatted number string:1.23456789E8[1243:403] Formatted number string:一億二千三百四十五萬六千七百八十九

如何獲取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_unspecifiedWKNavigation*)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的高度

CGFloat height= [[self.webView stringByEvaluatingJavaScriptFromString:@"document.body.offsetHeight"] floatValue];

navigationBar變為純透明

//第一種方法//導航欄純透明[self.navigationBar setBackgroundImage:[UIImagenew] forBarMetrics:UIBarMetricsDefault];//去掉導航欄底部的黑線self.navigationBar.shadowImage = [UIImagenew];//第二種方法[[self.navigationBar subviews] objectAtIndex:0].alpha =0;

tabBar同理

[self.tabBar setBackgroundImage:[UIImagenew]];self.tabBar.shadowImage = [UIImagenew];

navigationBar根據滑動距離的漸變色實現

//第一種- (void)scrollViewDidScroll:(UIScrollView*)scrollView{CGFloatoffsetToShow =200.0;//滑動多少就完全顯示CGFloatalpha =1- (offsetToShow - scrollView.contentOffset.y) / offsetToShow;? ? [[self.navigationController.navigationBar subviews] objectAtIndex:0].alpha = alpha;}

//第二種- (void)scrollViewDidScroll:(UIScrollView*)scrollView{CGFloatoffsetToShow =200.0;CGFloatalpha =1- (offsetToShow - scrollView.contentOffset.y) / offsetToShow;? ? [self.navigationController.navigationBar setShadowImage:[UIImagenew]];? ? [self.navigationController.navigationBar setBackgroundImage:[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.WebView stringByEvaluatingJavaScriptFromString:@"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= [NSString stringWithFormat:js,[UIScreen mainScreen].bounds.size.width-20];[webView stringByEvaluatingJavaScriptFromString:js];[webView stringByEvaluatingJavaScriptFromString:@"imgAutoFit()"];}

持續更新中……。

本文轉自:iOS_小松哥

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市,隨后出現的幾起案子,更是在濱河造成了極大的恐慌,老刑警劉巖,帶你破解...
    沈念sama閱讀 227,401評論 6 531
  • 序言:濱河連續發生了三起死亡事件,死亡現場離奇詭異,居然都是意外死亡,警方通過查閱死者的電腦和手機,發現死者居然都...
    沈念sama閱讀 98,011評論 3 413
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人,你說我怎么就攤上這事。” “怎么了?”我有些...
    開封第一講書人閱讀 175,263評論 0 373
  • 文/不壞的土叔 我叫張陵,是天一觀的道長。 經常有香客問我,道長,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 62,543評論 1 307
  • 正文 為了忘掉前任,我火速辦了婚禮,結果婚禮上,老公的妹妹穿的比我還像新娘。我一直安慰自己,他們只是感情好,可當我...
    茶點故事閱讀 71,323評論 6 404
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著,像睡著了一般。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發上,一...
    開封第一講書人閱讀 54,874評論 1 321
  • 那天,我揣著相機與錄音,去河邊找鬼。 笑死,一個胖子當著我的面吹牛,可吹牛的內容都是我干的。 我是一名探鬼主播,決...
    沈念sama閱讀 42,968評論 3 439
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了?” 一聲冷哼從身側響起,我...
    開封第一講書人閱讀 42,095評論 0 286
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后,有當地人在樹林里發現了一具尸體,經...
    沈念sama閱讀 48,605評論 1 331
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內容為張勛視角 年9月15日...
    茶點故事閱讀 40,551評論 3 354
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發現自己被綠了。 大學時的朋友給我發了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 42,720評論 1 369
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖,靈堂內的尸體忽然破棺而出,到底是詐尸還是另有隱情,我是刑警寧澤,帶...
    沈念sama閱讀 38,242評論 5 355
  • 正文 年R本政府宣布,位于F島的核電站,受9級特大地震影響,放射性物質發生泄漏。R本人自食惡果不足惜,卻給世界環境...
    茶點故事閱讀 43,961評論 3 345
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧,春花似錦、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 34,358評論 0 25
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至,卻和暖如春,著一層夾襖步出監牢的瞬間,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 35,612評論 1 280
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人。 一個月前我還...
    沈念sama閱讀 51,330評論 3 390
  • 正文 我出身青樓,卻偏偏與公主長得像,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當晚...
    茶點故事閱讀 47,690評論 2 370

推薦閱讀更多精彩內容

  • 原文 在這里總結一些iOS開發中的小技巧,能大大方便我們的開發,持續更新。 1.UITableView的Group...
    無灃閱讀 787評論 0 2
  • 在這里總結一些iOS開發中的小技巧,能大大方便我們的開發 原文地址:http://www.lxweimin.com/...
    Marray閱讀 335評論 0 0
  • 在這里總結一些iOS開發中的小技巧,能大大方便我們的開發,持續更新。 UITableView的Group樣式下頂部...
    UI愛好者閱讀 525評論 0 0
  • UITableView的Group樣式下頂部空白處理 //分組列表頭部空白處理UIView*view = [[UI...
    莫離_焱閱讀 425評論 0 0
  • 油紙傘輕輕飄 雨滴兒敲著窗 嘀嗒,嘀嗒 你靜靜的,守著它 思念的人兒在何方 終會歸來,一起守著它 油紙傘輕輕飄 雨...
    小棄閱讀 164評論 0 0