在這裡總結一些iOS開發中的小技巧,能大大方便我們的開發,持續更新。
UITableView的Group樣式下頂部空白處理
1 2 3 |
//分組列表頭部空白處理 UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 0, 0.1)]; self.tableView.tableHeaderView = view; |
UITableView的plain樣式下,取消區頭停滯效果
1 2 3 4 5 6 7 8 9 10 11 12 |
- (void)scrollViewDidScroll:(UIScrollView *)scrollView { CGFloat sectionHeaderHeight = sectionHead.height; if (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所在的控制器
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
- (UIViewController *)viewController { UIViewController *viewController = nil; UIResponder *next = self.nextResponder; while (next) { if ([next isKindOfClass:[UIViewController class]]) { viewController = (UIViewController *)next; break; } next = next.nextResponder; } return viewController; } |
兩種方法刪除NSUserDefaults所有記錄
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
//方法一 NSString *appDomain = [[NSBundle mainBundle] bundleIdentifier]; [[NSUserDefaults standardUserDefaults] removePersistentDomainForName:appDomain]; //方法二 - (void)resetDefaults { NSUserDefaults * defs = [NSUserDefaults standardUserDefaults]; NSDictionary * dict = [defs dictionaryRepresentation]; for (id key in dict) { [defs removeObjectForKey:key]; } [defs synchronize]; } |
列印系統所有已註冊的字型名稱
1 2 3 4 5 6 7 8 9 10 11 12 13 |
#pragma mark - 列印系統所有已註冊的字型名稱 void enumerateFonts() { for(NSString *familyName in [UIFont familyNames]) { NSLog(@"%@",familyName); NSArray *fontNames = [UIFont fontNamesForFamilyName:familyName]; for(NSString *fontName in fontNames) { NSLog(@"\t|- %@",fontName); } } } |
獲取圖片某一點的顏色
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 |
- (UIColor*) getPixelColorAtLocation:(CGPoint)point inImage:(UIImage *)image { UIColor* color = nil; CGImageRef inImage = image.CGImage; CGContextRef cgctx = [self createARGBBitmapContextFromImage:inImage]; if (cgctx == NULL) { return nil; /* error */ } size_t w = CGImageGetWidth(inImage); size_t h = CGImageGetHeight(inImage); CGRect rect = {{0,0},{w,h}}; CGContextDrawImage(cgctx, rect, inImage); unsigned char* data = CGBitmapContextGetData (cgctx); if (data != NULL) { int offset = 4*((w*round(point.y))+round(point.x)); int alpha = data[offset]; int red = data[offset+1]; int green = data[offset+2]; int blue = data[offset+3]; color = [UIColor colorWithRed:(red/255.0f) green:(green/255.0f) blue: (blue/255.0f) alpha:(alpha/255.0f)]; } CGContextRelease(cgctx); if (data) { free(data); } return color; } |
字串反轉
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
第一種: - (NSString *)reverseWordsInString:(NSString *)str { NSMutableString *newString = [[NSMutableString alloc] initWithCapacity:str.length]; for (NSInteger i = str.length - 1; i >= 0 ; i --) { unichar ch = [str characterAtIndex:i]; [newString appendFormat:@"%c", ch]; } return newString; } //第二種: - (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會鎖住螢幕。但有一些應用是不需要鎖屏的,比如視訊播放器。
1 2 3 |
[UIApplication sharedApplication].idleTimerDisabled = YES; 或 [[UIApplication sharedApplication] setIdleTimerDisabled:YES]; |
模態推出透明介面
1 2 3 4 5 6 7 8 9 10 11 12 13 |
UIViewController *vc = [[UIViewController alloc] init]; UINavigationController *na = [[UINavigationController alloc] initWithRootViewController:vc]; if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0) { na.modalPresentationStyle = UIModalPresentationOverCurrentContext; } else { self.modalPresentationStyle=UIModalPresentationCurrentContext; } [self presentViewController:na animated:YES completion:nil]; |
Xcode除錯不顯示記憶體佔用
1 |
editSCheme 裡面有個選項叫叫做enable zoombie Objects 取消選中 |
顯示隱藏檔案
1 2 3 4 5 6 7 |
//顯示 defaults write com.apple.finder AppleShowAllFiles -bool true killall Finder //隱藏 defaults write com.apple.finder AppleShowAllFiles -bool false killall Finder |
字串按多個符號分割
iOS跳轉到App Store下載應用評分
1 |
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"itms-apps://itunes.apple.com/WebObjects/MZStore.woa/wa/viewContentsUserReviews?type=Purple+Software&id=APPID"]]; |
iOS 獲取漢字的拼音
1 2 3 4 5 6 7 8 9 10 11 12 13 |
+ (NSString *)transform:(NSString *)chinese { //將NSString裝換成NSMutableString NSMutableString *pinyin = [chinese mutableCopy]; //將漢字轉換為拼音(帶音標) CFStringTransform((__bridge CFMutableStringRef)pinyin, NULL, kCFStringTransformMandarinLatin, NO); NSLog(@"%@", pinyin); //去掉拼音的音標 CFStringTransform((__bridge CFMutableStringRef)pinyin, NULL, kCFStringTransformStripCombiningMarks, NO); NSLog(@"%@", pinyin); //返回最近結果 return pinyin; } |
手動更改iOS狀態列的顏色
1 2 3 4 5 6 7 8 9 |
- (void)setStatusBarBackgroundColor:(UIColor *)color { UIView *statusBar = [[[UIApplication sharedApplication] valueForKey:@"statusBarWindow"] valueForKey:@"statusBar"]; if ([statusBar respondsToSelector:@selector(setBackgroundColor:)]) { statusBar.backgroundColor = color; } } |
判斷當前ViewController是push還是present的方式顯示的
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
NSArray *viewcontrollers=self.navigationController.viewControllers; if (viewcontrollers.count > 1) { if ([viewcontrollers objectAtIndex:viewcontrollers.count - 1] == self) { //push方式 [self.navigationController popViewControllerAnimated:YES]; } } else { //present方式 [self dismissViewControllerAnimated:YES completion:nil]; } |
獲取實際使用的LaunchImage圖片
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
- (NSString *)getLaunchImageName { CGSize viewSize = self.window.bounds.size; // 豎屏 NSString *viewOrientation = @"Portrait"; NSString *launchImageName = nil; NSArray* imagesDict = [[[NSBundle mainBundle] infoDictionary] valueForKey:@"UILaunchImages"]; for (NSDictionary* dict in imagesDict) { CGSize imageSize = CGSizeFromString(dict[@"UILaunchImageSize"]); if (CGSizeEqualToSize(imageSize, viewSize) && [viewOrientation isEqualToString:dict[@"UILaunchImageOrientation"]]) { launchImageName = dict[@"UILaunchImageName"]; } } return launchImageName; } |
iOS在當前螢幕獲取第一響應
1 2 |
UIWindow * keyWindow = [[UIApplication sharedApplication] keyWindow]; UIView * firstResponder = [keyWindow performSelector:@selector(firstResponder)]; |
判斷物件是否遵循了某協議
1 2 3 4 |
if ([self.selectedController conformsToProtocol:@protocol(RefreshPtotocol)]) { [self.selectedController performSelector:@selector(onTriggerRefresh)]; } |
判斷view是不是指定檢視的子檢視
1 |
BOOL isView = [textView isDescendantOfView:self.view]; |
NSArray 快速求總和 最大值 最小值 和 平均值
1 2 3 4 5 6 |
NSArray *array = [NSArray arrayWithObjects:@"2.0", @"2.3", @"3.0", @"4.0", @"10", nil]; CGFloat sum = [[array valueForKeyPath:@"@sum.floatValue"] floatValue]; CGFloat avg = [[array valueForKeyPath:@"@avg.floatValue"] floatValue]; CGFloat max =[[array valueForKeyPath:@"@max.floatValue"] floatValue]; CGFloat min =[[array valueForKeyPath:@"@min.floatValue"] floatValue]; NSLog(@"%f\n%f\n%f\n%f",sum,avg,max,min); |
修改UITextField中Placeholder的文字顏色
1 |
[textField setValue:[UIColor redColor] forKeyPath:@"_placeholderLabel.textColor"]; |
關於NSDateFormatter的格式
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
G: 公元時代,例如AD公元 yy: 年的後2位 yyyy: 完整年 MM: 月,顯示為1-12 MMM: 月,顯示為英文月份簡寫,如 Jan MMMM: 月,顯示為英文月份全稱,如 Janualy dd: 日,2位數表示,如02 d: 日,1-2位顯示,如 2 EEE: 簡寫星期幾,如Sun EEEE: 全寫星期幾,如Sunday aa: 上下午,AM/PM H: 時,24小時制,0-23 K:時,12小時制,0-11 m: 分,1-2位 mm: 分,2位 s: 秒,1-2位 ss: 秒,2位 S: 毫秒 |
獲取一個類的所有子類
1 2 3 4 5 6 7 |
+ (NSArray *) allSubclasses { Class myClass = [self class]; NSMutableArray *mySubclasses = [NSMutableArray array]; unsigned int numOfClasses; Class *classes = objc_copyClassList(&numOfClasses;); for (unsigned int ci = 0; ci |
監測IOS裝置是否設定了代理,需要CFNetwork.framework
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
NSDictionary *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(@"設定了代理"); } |
阿拉伯數字轉中文格式
1 2 3 4 5 6 7 8 9 10 |
+(NSString *)translation:(NSString *)arebic { NSString *str = arebic; NSArray *arabic_numerals = @[@"1",@"2",@"3",@"4",@"5",@"6",@"7",@"8",@"9",@"0"]; NSArray *chinese_numerals = @[@"一",@"二",@"三",@"四",@"五",@"六",@"七",@"八",@"九",@"零"]; NSArray *digits = @[@"個",@"十",@"百",@"千",@"萬",@"十",@"百",@"千",@"億",@"十",@"百",@"千",@"兆"]; NSDictionary *dictionary = [NSDictionary dictionaryWithObjects:chinese_numerals forKeys:arabic_numerals]; NSMutableArray *sums = [NSMutableArray array]; for (int i = 0; i |
Base64編碼與NSString物件或NSData物件的轉換
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
// Create NSData object NSData *nsdata = [@"iOS Developer Tips encoded in Base64" dataUsingEncoding:NSUTF8StringEncoding]; // Get NSString from NSData object in Base64 NSString *base64Encoded = [nsdata base64EncodedStringWithOptions:0]; // Print the Base64 encoded string NSLog(@"Encoded: %@", base64Encoded); // Let's go the other way... // NSData from the Base64 encoded str NSData *nsdataFromBase64String = [[NSData alloc] initWithBase64EncodedString:base64Encoded options:0]; // Decoded NSString from the NSData NSString *base64Decoded = [[NSString alloc] initWithData:nsdataFromBase64String encoding:NSUTF8StringEncoding]; NSLog(@"Decoded: %@", base64Decoded); |
取消UICollectionView的隱式動畫
UICollectionView在reloadItems的時候,預設會附加一個隱式的fade動畫,有時候很討厭,尤其是當你的cell是複合cell的情況下(比如cell使用到了UIStackView)。
下面幾種方法都可以幫你去除這些動畫
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
//方法一 [UIView performWithoutAnimation:^{ [collectionView reloadItemsAtIndexPaths:@[[NSIndexPath indexPathForItem:index inSection:0]]]; }]; //方法二 [UIView animateWithDuration:0 animations:^{ [collectionView performBatchUpdates:^{ [collectionView reloadItemsAtIndexPaths:@[[NSIndexPath indexPathForItem:index inSection:0]]]; } completion:nil]; }]; //方法三 [UIView setAnimationsEnabled:NO]; [self.trackPanel performBatchUpdates:^{ [collectionView reloadItemsAtIndexPaths:@[[NSIndexPath indexPathForItem:index inSection:0]]]; } completion:^(BOOL finished) { [UIView setAnimationsEnabled:YES]; }]; |
讓Xcode的控制檯支援LLDB型別的列印
1 2 3 4 |
開啟終端輸入三條命令: touch ~/.lldbinit echo display @import UIKit >> ~/.lldbinit echo target stop-hook add -o \"target stop-hook disable\" >> ~/.lldbinit |
CocoaPods pod install/pod update更新慢的問題
1 2 3 |
pod install --verbose --no-repo-update pod update --verbose --no-repo-update 如果不加後面的引數,預設會升級CocoaPods的spec倉庫,加一個引數可以省略這一步,然後速度就會提升不少 |
UIImage 佔用記憶體大小
1 2 |
UIImage *image = [UIImage imageNamed:@"aa"]; NSUInteger size = CGImageGetHeight(image.CGImage) * CGImageGetBytesPerRow(image.CGImage); |
GCD timer定時器
1 2 3 4 5 6 7 8 9 10 11 |
dispatch_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_source_cancel(timer); dispatch_async(dispatch_get_main_queue(), ^{ }); }); dispatch_resume(timer); |
圖片上繪製文字 寫一個UIImage的category
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
- (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:NSStringDrawingUsesLineFragmentOrigin attributes:@{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; } |
查詢一個檢視的所有子檢視
1 2 3 4 5 6 7 8 9 10 11 12 13 |
- (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; } |
計算檔案大小
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 |
//檔案大小 - (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; } |
UIView設定部分圓角
你是不是也遇到過這樣的問題,一個button或者label,只要右邊的兩個角圓角,或者只要一個圓角。該怎麼辦呢。這就需要圖層蒙版來幫助我們了
1 2 3 4 5 6 7 8 |
CGRect rect = view.bounds; CGSize radio = CGSizeMake(30, 30);//圓角尺寸 UIRectCorner corner = UIRectCornerTopLeft|UIRectCornerTopRight;//這隻圓角位置 UIBezierPath *path = [UIBezierPath bezierPathWithRoundedRect:rect byRoundingCorners:corner cornerRadii:radio]; CAShapeLayer *masklayer = [[CAShapeLayer alloc]init];//建立shapelayer masklayer.frame = view.bounds; masklayer.path = path.CGPath;//設定路徑 view.layer.mask = masklayer; |
取上整與取下整
1 2 3 4 5 6 7 8 9 10 |
floor(x),有時候也寫做Floor(x),其功能是“下取整”,即取不大於x的最大整數 例如: x=3.14,floor(x)=3 y=9.99999,floor(y)=9 與floor函式對應的是ceil函式,即上取整函式。 ceil函式的作用是求不小於給定實數的最小整數。 ceil(2)=ceil(1.2)=cei(1.5)=2.00 floor函式與ceil函式的返回值均為double型 |
計算字串字元長度,一個漢字算兩個字元
1 2 3 4 5 6 |
//方法一: - (int)convertToInt:(NSString*)strtemp { int strlength = 0; char* p = (char*)[strtemp cStringUsingEncoding:NSUnicodeStringEncoding]; for (int i=0 ; i |
給UIView設定圖片
1 2 3 |
UIImage *image = [UIImage imageNamed:@"image"]; self.MYView.layer.contents = (__bridge id _Nullable)(image.CGImage); self.MYView.layer.contentsRect = CGRectMake(0, 0, 0.5, 0.5); |
防止scrollView手勢覆蓋側滑手勢
1 |
[scrollView.panGestureRecognizerrequireGestureRecognizerToFail:self.navigationController.interactivePopGestureRecognizer]; |
去掉導航欄返回的back標題
1 |
[[UIBarButtonItemappearance]setBackButtonTitlePositionAdjustment:UIOffsetMake(0, -60)forBarMetrics:UIBarMetricsDefault]; |
字串中是否含有中文
1 2 3 |
+ (BOOL)checkIsChinese:(NSString *)string { for (int i=0; i |
dispatch_group的使用
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
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每四位加一個空格,實現代理
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string { // 四位加一個空格 if ([string isEqualToString:@""]) { // 刪除字元 if ((textField.text.length - 2) % 5 == 0) { textField.text = [textField.text substringToIndex:textField.text.length - 1]; } return YES; } else { if (textField.text.length % 5 == 0) { textField.text = [NSString stringWithFormat:@"%@ ", textField.text]; } } return YES; } |
獲取私有屬性和成員變數 #import
1 2 3 4 5 6 7 |
//獲取私有屬性 比如設定UIDatePicker的字型顏色 - (void)setTextColor { //獲取所有的屬性,去檢視有沒有對應的屬性 unsigned int count = 0; objc_property_t *propertys = class_copyPropertyList([UIDatePicker class], &count); for(int i = 0;i |
1 2 3 4 |
//獲得成員變數 比如修改UIAlertAction的按鈕字型顏色 unsigned int count = 0; Ivar *ivars = class_copyIvarList([UIAlertAction class], &count); for(int i =0;i |
獲取手機安裝的應用
1 2 3 4 5 6 7 8 9 10 |
Class 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")]); } |
判斷兩個日期是否在同一周 寫在NSDate的category裡面
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
- (BOOL)isSameDateWithDate:(NSDate *)date { //日期間隔大於七天之間返回NO if (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; } |
應用內開啟系統設定介面
1 2 3 |
//iOS8之後 [[UIApplication sharedApplication] openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString]]; //如果App沒有新增許可權,顯示的是設定介面。如果App有新增許可權(例如通知),顯示的是App的設定介面。 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 |
//iOS8之前 //先新增一個url type如下圖,在程式碼中呼叫如下程式碼,即可跳轉到設定頁面的對應項 [[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"prefs:root=WIFI"]]; 可選值如下: About — prefs:root=General&path=About Accessibility — prefs:root=General&path=ACCESSIBILITY Airplane Mode On — prefs:root=AIRPLANE_MODE Auto-Lock — prefs:root=General&path=AUTOLOCK Brightness — prefs:root=Brightness Bluetooth — prefs:root=General&path=Bluetooth Date & Time — prefs:root=General&path=DATE_AND_TIME FaceTime — prefs:root=FACETIME General — prefs:root=General Keyboard — prefs:root=General&path=Keyboard iCloud — prefs:root=CASTLE iCloud Storage & Backup — prefs:root=CASTLE&path=STORAGE_AND_BACKUP International — prefs:root=General&path=INTERNATIONAL Location Services — prefs:root=LOCATION_SERVICES Music — prefs:root=MUSIC Music Equalizer — prefs:root=MUSIC&path=EQ Music Volume Limit — prefs:root=MUSIC&path=VolumeLimit Network — prefs:root=General&path=Network Nike + iPod — prefs:root=NIKE_PLUS_IPOD Notes — prefs:root=NOTES Notification — prefs:root=NOTIFICATI*****_ID Phone — prefs:root=Phone Photos — prefs:root=Photos Profile — prefs:root=General&path=ManagedConfigurationList Reset — prefs:root=General&path=Reset Safari — prefs:root=Safari Siri — prefs:root=General&path=Assistant Sounds — prefs:root=Sounds Software Update — prefs:root=General&path=SOFTWARE_UPDATE_LINK Store — prefs:root=STORE Twitter — prefs:root=TWITTER Usage — prefs:root=General&path=USAGE VPN — prefs:root=General&path=Network/VPN Wallpaper — prefs:root=Wallpaper Wi-Fi — prefs:root=WIFI |
遮蔽觸發事件,2秒後取消遮蔽
1 2 3 4 |
[[UIApplication sharedApplication] beginIgnoringInteractionEvents]; dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{ [[UIApplication sharedApplication] endIgnoringInteractionEvents] }); |
動畫暫停再開始
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
-(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; } |
fillRule原理
iOS中數字的格式化
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
//通過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,它是一個列舉型,設定不同的值可以輸出不同的數字格式。該列舉包括: typedef NS_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獲取圖片和新增點選的識別方式
1 2 3 4 5 6 7 8 9 |
//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 |
1 2 3 4 5 6 7 8 |
//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 |
獲取到webview的高度
1 |
CGFloat height = [[self.webView stringByEvaluatingJavaScriptFromString:@"document.body.offsetHeight"] floatValue]; |
navigationBar變為純透明
1 2 3 4 5 6 7 8 |
//第一種方法 //導航欄純透明 [self.navigationBar setBackgroundImage:[UIImage new] forBarMetrics:UIBarMetricsDefault]; //去掉導航欄底部的黑線 self.navigationBar.shadowImage = [UIImage new]; //第二種方法 [[self.navigationBar subviews] objectAtIndex:0].alpha = 0; |
tabBar同理
1 2 |
[self.tabBar setBackgroundImage:[UIImage new]]; self.tabBar.shadowImage = [UIImage new]; |
navigationBar根據滑動距離的漸變色實現
1 2 3 4 5 6 7 |
//第一種 - (void)scrollViewDidScroll:(UIScrollView *)scrollView { CGFloat offsetToShow = 200.0;//滑動多少就完全顯示 CGFloat alpha = 1 - (offsetToShow - scrollView.contentOffset.y) / offsetToShow; [[self.navigationController.navigationBar subviews] objectAtIndex:0].alpha = alpha; } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
//第二種 - (void)scrollViewDidScroll:(UIScrollView *)scrollView { CGFloat offsetToShow = 200.0; CGFloat alpha = 1 - (offsetToShow - scrollView.contentOffset.y) / offsetToShow; [self.navigationController.navigationBar setShadowImage:[UIImage new]]; [self.navigationController.navigationBar setBackgroundImage:[self imageWithColor:[[UIColor orangeColor]colorWithAlphaComponent:alpha]] forBarMetrics:UIBarMetricsDefault]; } //生成一張純色的圖片 - (UIImage *)imageWithColor:(UIColor *)color { CGRect rect = CGRectMake(0.0f, 0.0f, 1.0f, 1.0f); UIGraphicsBeginImageContext(rect.size); CGContextRef context = UIGraphicsGetCurrentContext(); CGContextSetFillColorWithColor(context, [color CGColor]); CGContextFillRect(context, rect); UIImage *theImage = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); return theImage; } |
iOS 開發中一些相關的路徑
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
模擬器的位置: /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會和螢幕右側保持一段距離:
下面是通過新增一個負值寬度的固定間距的item來解決,也可以改變寬度實現不同的間隔:
1 2 3 4 5 6 7 8 |
UIImage *img = [[UIImage imageNamed:@"icon_cog"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal]; //寬度為負數的固定間距的系統item UIBarButtonItem *rightNegativeSpacer = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace target:nil action:nil]; [rightNegativeSpacer setWidth:-15]; UIBarButtonItem *rightBtnItem1 = [[UIBarButtonItem alloc]initWithImage:img style:UIBarButtonItemStylePlain target:self action:@selector(rightButtonItemClicked:)]; UIBarButtonItem *rightBtnItem2 = [[UIBarButtonItem alloc]initWithImage:img style:UIBarButtonItemStylePlain target:self action:@selector(rightButtonItemClicked:)]; self.navigationItem.rightBarButtonItems = @[rightNegativeSpacer,rightBtnItem1,rightBtnItem2]; |
NSString進行URL編碼和解碼
1 2 3 4 5 6 7 |
NSString *string = @"http://abc.com?aaa=你好&bbb=tttee"; //編碼 列印:http://abc.com?aaa=%E4%BD%A0%E5%A5%BD&bbb=tttee string = [string stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]]; //解碼 列印:http://abc.com?aaa=你好&bbb=tttee string = [string stringByRemovingPercentEncoding]; |
UIWebView設定User-Agent。
1 2 3 4 5 |
//設定 NSDictionary *dic = @{@"UserAgent":@"your UserAgent"}; [[NSUserDefaults standardUserDefaults] registerDefaults:dic]; //獲取 NSString *agent = [self.WebView stringByEvaluatingJavaScriptFromString:@"navigator.userAgent"]; |
獲取硬碟總容量與可用容量:
1 2 3 4 5 |
NSFileManager *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)); |
獲取UIColor的RGBA值
1 2 3 4 5 6 |
UIColor *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]); |
修改textField的placeholder的字型顏色、大小
1 2 |
[self.textField setValue:[UIColor redColor] forKeyPath:@"_placeholderLabel.textColor"]; [self.textField setValue:[UIFont boldSystemFontOfSize:16] forKeyPath:@"_placeholderLabel.font"]; |
AFN移除JSON中的NSNull
1 2 |
AFJSONResponseSerializer *response = [AFJSONResponseSerializer serializer]; response.removesKeysWithNullValues = YES; |
ceil()和floor()
ceil()
功 能:返回大於或者等於指定表示式的最小整數
floor()
功 能:返回小於或者等於指定表示式的最大整數
UIWebView裡面的圖片自適應螢幕
在webView載入完的代理方法裡面這樣寫:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
- (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()"]; } |
持續更新中……。