UITableView的Group樣式下頂部空白處理
//分組列表頭部空白處理UIView*view = [[UIViewalloc] initWithFrame:CGRectMake(0,0,0,0.1)];self.tableView.tableHeaderView= view;
UITableView的plain樣式下死嗦,取消區(qū)頭停滯效果
- (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樣式吧哈哈。
- (UIViewController*)viewController{UIViewController*viewController =nil;UIResponder*next=self.nextResponder;while(next)? {if([nextisKindOfClass:[UIViewControllerclass]]){? ? ? viewController = (UIViewController*)next;break;? ? ? ? }next=next.nextResponder;? ? }returnviewController;}
//方法一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 - 打印系統(tǒng)所有已注冊的字體名稱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];
editSCheme? 里面有個選項叫叫做enablezoombie Objects? 取消選中
//顯示defaults write com.apple.finderAppleShowAllFiles -booltruekillall Finder//隱藏defaults write com.apple.finderAppleShowAllFiles -boolfalsekillall Finder
image.png
[[UIApplication sharedApplication]openURL:[NSURL URLWithString:@"itms-apps://itunes.apple.com/WebObjects/MZStore.woa/wa/viewContentsUserReviews?type=Purple+Software&id=APPID"]];
+ (NSString*)transform:(NSString*)chinese{//將NSString裝換成NSMutableStringNSMutableString*pinyin = [chinese mutableCopy];//將漢字轉(zhuǎn)換為拼音(帶音標)CFStringTransform((__bridgeCFMutableStringRef)pinyin,NULL, kCFStringTransformMandarinLatin,NO);NSLog(@"%@", pinyin);//去掉拼音的音標CFStringTransform((__bridgeCFMutableStringRef)pinyin,NULL, kCFStringTransformStripCombiningMarks,NO);NSLog(@"%@", pinyin);//返回最近結(jié)果returnpinyin; }
- (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];}
- (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;}
UIWindow* keyWindow = [[UIApplicationsharedApplication] keyWindow];UIView* firstResponder = [keyWindow performSelector:@selector(firstResponder)];
if([self.selectedControllerconformsToProtocol:@protocol(RefreshPtotocol)]){? ? [self.selectedControllerperformSelector:@selector(onTriggerRefresh)];}
BOOLisView = [textView isDescendantOfView:self.view];
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"];
G: 公元時代,例如AD公元yy: 年的后2位yyyy: 完整年MM: 月八酒,顯示為1-12MMM: 月空民,顯示為英文月份簡寫,如 JanMMMM: 月,顯示為英文月份全稱羞迷,如 Janualydd: 日界轩,2位數(shù)表示,如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;}
監(jiān)測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對象的轉(zhuǎn)換
// 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在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];}];
打開終端輸入三條命令: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如果不加后面的參數(shù)髓涯,默認會升級CocoaPods的spec倉庫,加一個參數(shù)可以省略這一步哈扮,然后速度就會提升不少
UIImage*image = [UIImageimageNamed:@"aa"];NSUIntegersize? =CGImageGetHeight(image.CGImage) *CGImageGetBytesPerRow(image.CGImage);
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);//每秒執(zhí)行dispatch_source_set_event_handler(timer, ^{//@"倒計時結(jié)束纬纪,關閉"dispatch_source_cancel(timer);? ? dispatch_async(dispatch_get_main_queue(), ^{? ? });});dispatch_resume(timer);
- (UIImage*)imageWithTitle:(NSString*)title fontSize:(CGFloat)fontSize{//畫布大小CGSizesize=CGSizeMake(self.size.width,self.size.height);//創(chuàng)建一個基于位圖的上下文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;}
你是不是也遇到過這樣的問題蚓再,一個button或者label,只要右邊的兩個角圓角包各,或者只要一個圓角摘仅。該怎么辦呢。這就需要圖層蒙版來幫助我們了
CGRectrect = view.bounds;CGSizeradio =CGSizeMake(30,30);//圓角尺寸UIRectCornercorner =UIRectCornerTopLeft|UIRectCornerTopRight;//這只圓角位置UIBezierPath*path = [UIBezierPathbezierPathWithRoundedRect:rect byRoundingCorners:corner cornerRadii:radio];CAShapeLayer*masklayer = [[CAShapeLayeralloc]init];//創(chuàng)建shapelayermasklayer.frame= view.bounds;masklayer.path= path.CGPath;//設置路徑view.layer.mask= masklayer;
floor(x),有時候也寫做Floor(x)问畅,其功能是“下取整”娃属,即取不大于x的最大整數(shù) 例如:x=3.14,floor(x)=3y=9.99999护姆,floor(y)=9與floor函數(shù)對應的是ceil函數(shù)矾端,即上取整函數(shù)。ceil函數(shù)的作用是求不小于給定實數(shù)的最小整數(shù)卵皂。ceil(2)=ceil(1.2)=cei(1.5)=2.00floor函數(shù)與ceil函數(shù)的返回值均為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;}
UIImage*image = [UIImageimageNamed:@"image"];self.MYView.layer.contents= (__bridgeid_Nullable)(image.CGImage);self.MYView.layer.contentsRect=CGRectMake(0,0,0.5,0.5);
[scrollView.panGestureRecognizerrequireGestureRecognizerToFail:self.navigationController.interactivePopGestureRecognizer];
[[UIBarButtonItemappearance]setBackButtonTitlePositionAdjustment:UIOffsetMake(0, -60)forBarMetrics:UIBarMetricsDefault];
+ (BOOL)checkIsChinese:(NSString *)string{for(inti=0; i
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每四位加一個空格,實現(xiàn)代理
- (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;}
//獲取私有屬性 比如設置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沒有添加權(quán)限殴玛,顯示的是設定界面。如果App有添加權(quán)限(例如通知)添祸,顯示的是App的設定界面滚粟。
//iOS8之前//先添加一個url type如下圖,在代碼中調(diào)用如下代碼,即可跳轉(zhuǎn)到設置頁面的對應項[[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
-(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;}
Image.png
//通過NSNumberFormatter膝捞,同樣可以設置NSNumber輸出的格式坦刀。例如如下代碼:NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];formatter.numberStyle = NSNumberFormatterDecimalStyle;NSString *string= [formatter stringFromNumber:[NSNumber numberWithInt:123456789]];NSLog(@"Formatted number string:%@",string);//輸出結(jié)果為:[1223:403] Formatted number string:123,456,789//其中NSNumberFormatter類有個屬性numberStyle,它是一個枚舉型蔬咬,設置不同的值可以輸出不同的數(shù)字格式鲤遥。該枚舉包括:typedefNS_ENUM(NSUInteger, NSNumberFormatterStyle){? ? NSNumberFormatterNoStyle = kCFNumberFormatterNoStyle,? ? NSNumberFormatterDecimalStyle = kCFNumberFormatterDecimalStyle,? ? NSNumberFormatterCurrencyStyle = kCFNumberFormatterCurrencyStyle,? ? NSNumberFormatterPercentStyle = kCFNumberFormatterPercentStyle,? ? NSNumberFormatterScientificStyle = kCFNumberFormatterScientificStyle,? ? NSNumberFormatterSpellOutStyle = kCFNumberFormatterSpellOutStyle};//各個枚舉對應輸出數(shù)字格式的效果如下:其中第三項和最后一項的輸出會根據(jù)系統(tǒng)設置的語言區(qū)域的不同而不同。[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:一億二千三百四十五萬六千七百八十九
在網(wǎng)頁加載完成時盖奈,通過js獲取圖片和添加點擊的識別方式
//UIWebView- (void)webViewDidFinishLoad:(UIWebView*)webView{//這里是js,主要目的實現(xiàn)對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的數(shù)組}
//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);? ? }];}
CGFloatheight = [[self.webViewstringByEvaluatingJavaScriptFromString:@"document.body.offsetHeight"] floatValue];
//第一種方法//導航欄純透明[self.navigationBarsetBackgroundImage:[UIImagenew] forBarMetrics:UIBarMetricsDefault];//去掉導航欄底部的黑線self.navigationBar.shadowImage= [UIImagenew];//第二種方法[[self.navigationBarsubviews] objectAtIndex:0].alpha=0;
[self.tabBarsetBackgroundImage:[UIImagenew]];self.tabBar.shadowImage= [UIImagenew];
navigationBar根據(jù)滑動距離的漸變色實現(xiàn)
//第一種- (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;}
模擬器的位置:/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會和屏幕右側(cè)保持一段距離:
image.png
下面是通過添加一個負值寬度的固定間距的item來解決,也可以改變寬度實現(xiàn)不同的間隔:
UIImage*img = [[UIImageimageNamed:@"icon_cog"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];//寬度為負數(shù)的固定間距的系統(tǒng)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];