GCD定時器 圖片上繪製文字 查找一個視圖的所有子視圖 計算文件大小 UIView的設置部分圓角 計算字元串字元長度,一個漢字算兩個字元 防止滾動視圖手勢覆蓋側滑手勢 去掉導航欄返回的標題 字元串中是否含有中文 dispatch_group的使用 UITextField每四位加一個空格,實現代理 獲 ...
GCD定時器
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 *)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; }
查找一個視圖的所有子視圖
- (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; }
計算文件大小
//文件大小 - (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的設置部分圓角
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;
計算字元串字元長度,一個漢字算兩個字元
//方法一: - (int)convertToInt:(NSString*)strtemp { int strlength = 0; char* p = (char*)[strtemp cStringUsingEncoding:NSUnicodeStringEncoding]; for (int i=0 ; i<[strtemp lengthOfBytesUsingEncoding:NSUnicodeStringEncoding] ;i++) { if (*p) { p++; strlength++; } else { p++; } } return strlength; } //方法二: -(NSUInteger) unicodeLengthOfString: (NSString *) text { NSUInteger asciiLength = 0; for (NSUInteger i = 0; i < text.length; i++) { unichar uc = [text characterAtIndex: i]; asciiLength += isascii(uc) ? 1 : 2; } return asciiLength; }
防止滾動視圖手勢覆蓋側滑手勢
[scrollView.panGestureRecognizer requireGestureRecognizerToFail:self.navigationController.interactivePopGestureRecognizer];
去掉導航欄返回的標題
[[UIBarButtonItem appearance]setBackButtonTitlePositionAdjustment:UIOffsetMake(0, -60)forBarMetrics:UIBarMetricsDefault];
字元串中是否含有中文
+ (BOOL)checkIsChinese:(NSString *)string { for (int i=0; i<string.length; i++) { unichar ch = [string characterAtIndex:i]; if (0x4E00 <= ch && ch <= 0x9FA5) { return YES; } } return NO; }
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 ([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; }
獲取手機安裝的應用
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(@"bundleVersion")]); NSLog(@"%@",[item performSelector:NSSelectorFromString(@"shortVersionString")]); }
應用內打開系統設置界面
//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=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
動畫暫停再開始
-(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; }
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,它是一個枚舉型,設置不同的值可以輸出不同的數字格式。該枚舉包括: 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所有的圖片地址
//UIWebView - (void)webViewDidFinishLoad:(UIWebView *)webView { //這裡是js,主要目的實現對url的獲取 static NSString * const jsGetImages = @"function getImages(){\ var objs = document.getElementsByTagName(\"img\");\ var imgScr = '';\ for(var i=0;i<objs.length;i++){\ imgScr = imgScr + objs[i].src + '+';\ };\ return imgScr;\ };"; [webView stringByEvaluatingJavaScriptFromString:jsGetImages];//註入js方法 NSString *urlResult = [webView stringByEvaluatingJavaScriptFromString:@"getImages()"]; NSArray *urlArray = [NSMutableArray arrayWithArray:[urlResult componentsSeparatedByString:@"+"]]; //urlResurlt 就是獲取到得所有圖片的url的拼接;mUrlArray就是所有Url的數組 } //WKWebView - (void)webView:(WKWebView *)webView didFinishNavigation:(null_unspecified WKNavigation *)navigation { static NSString * const jsGetImages = @"function getImages(){\ var objs = document.getElementsByTagName(\"img\");\ var imgScr = '';\ for(var i=0;i<objs.length;i++){\ imgScr = imgScr + objs[i].src + '+';\ };\ return imgScr;\ };"; [webView evaluateJavaScript:jsGetImages completionHandler:nil]; [webView evaluateJavaScript:@"getImages()" completionHandler:^(id _Nullable result, NSError * _Nullable error) { NSLog(@"%@",result); }]; }
獲取到的WebView的高度
CGFloat height = [[self.webView stringByEvaluatingJavaScriptFromString:@"document.body.offsetHeight"] floatValue];
導航欄變為純透明
//第一種方法 //導航欄純透明 [self.navigationBar setBackgroundImage:[UIImage new] forBarMetrics:UIBarMetricsDefault]; //去掉導航欄底部的黑線 self.navigationBar.shadowImage = [UIImage new]; //第二種方法 [[self.navigationBar subviews] objectAtIndex:0].alpha = 0;
tabBar變為純透明
[self.tabBar setBackgroundImage:[UIImage new]]; self.tabBar.shadowImage = [UIImage new];
navigationBar根據滑動距離的漸變色實現
//第一種 - (void)scrollViewDidScroll:(UIScrollView *)scrollView { CGFloat offsetToShow = 200.0;//滑動多少就完全顯示 CGFloat alpha = 1 - (offsetToShow - scrollView.contentOffset.y) / offsetToShow; [[self.navigationController.navigationBar subviews] objectAtIndex:0].alpha = alpha; } //第二種 - (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; }
小伙伴們,今天就分享到這裡,希望大家有所收穫!O(∩_∩)O哈哈~