一. 顏色漸變
CAGradientLayer *gradientLayer = [CAGradientLayer layer];
gradientLayer.colors = @[(__bridge id)[UIColor whiteColor].CGColor, (__bridge id)[UIColor grayColor].CGColor, (__bridge id)[UIColor whiteColor].CGColor];
gradientLayer.locations = @[@0.0, @0.5, @1.0];
gradientLayer.startPoint = CGPointMake(0, 0);
gradientLayer.endPoint = CGPointMake(1.0, 0);
gradientLayer.frame = CGRectMake(0, 100, 300, 2);
[self.view.layer addSublayer:gradientLayer];
二. (已刪除)
三. 使用drowRect繪制簡單圖形
//獲取上下文
CGContextRef context=UIGraphicsGetCurrentContext();
//設置繪制地區(qū)的顏色
CGContextSetRGBFillColor(context, 1, 0, 0, 1);
//設置繪制的位置和大小
CGContextFillRect(context, CGRectMake(0, 100, 100, 100));
NSString * text=@"文字";
UIFont * font=[UIFont systemFontOfSize:14];
//設置文字的位置
[text drawAtPoint:CGPointMake(0, 200) withAttributes:font.fontDescriptor.fontAttributes];
UIImage * img=[UIImage imageNamed:@""];
[img drawInRect:CGRectMake(0, 300, 100, 100)];
四. 可變數(shù)組與不可變數(shù)組之間的轉(zhuǎn)換
NSMutableArray * mutablearray=[[NSMutableArray alloc]initWithCapacity:0];
NSArray * copyarray=[mutablearray copy];
copyarray=@[@"1",@"2",@"3"];
NSArray * array=[[NSArray alloc]init];
NSMutableArray * copymutablearray=[array mutableCopy];
[copymutablearray setObject:@"加入到第一位" atIndexedSubscript:0];
[copymutablearray addObject:@"排序加入"];
[copymutablearray addObjectsFromArray:copyarray];
五. 快速求和,最大值恰画,最小值,平均值
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];
六. 對控件的旋轉(zhuǎn)疫剃,平移,縮放,復位
//平移
CGAffineTransform transForm = _pingyibu.transform;
_pingyibu.transform=CGAffineTransformTranslate(transForm, 100, 0);
//旋轉(zhuǎn)
_pingyibu.transform = CGAffineTransformRotate(transForm, M_PI_4);
//縮放按鈕
_pingyibu.transform = CGAffineTransformScale(transForm, 1.2, 1.2);
//初始化復位
_pingyibu.transform = CGAffineTransformIdentity;
七. 設置label的行間距
NSMutableAttributedString *attributedString =
[[NSMutableAttributedString alloc] initWithString:_xuanzhuanla.text];
NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
[paragraphStyle setLineSpacing:3];
//調(diào)整行間距
[attributedString addAttribute:NSParagraphStyleAttributeName
value:paragraphStyle
range:NSMakeRange(0, [_xuanzhuanla.text length])];
_xuanzhuanla.attributedText = attributedString;
八. 讓應用直接閃退
AppDelegate *app = [UIApplication sharedApplication].delegate;
UIWindow *window = app.window;
[UIView animateWithDuration:1.0f animations:^{
window.alpha = 0;
} completion:^(BOOL finished) {
exit(0);
}];
九. 手機震動
AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);
十. 生成手機唯一ID:UUID
-(NSString*) uuid {
CFUUIDRef puuid = CFUUIDCreate( nil );
CFStringRef uuidString = CFUUIDCreateString( nil, puuid );
NSString * result = (NSString *)CFBridgingRelease(CFStringCreateCopy( NULL, uuidString));
CFRelease(puuid);
CFRelease(uuidString);
return result;
}
十一. label自適應高度
CGRect rect=[la.text boundingRectWithSize:CGSizeMake(WIDTH-70, MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin|NSStringDrawingUsesFontLeading attributes:@{NSFontAttributeName:la.font} context:nil];
十二. 使用AFN判斷網(wǎng)絡狀態(tài)
NSURL *url=[NSURL URLWithString:@"http://www.apple.com"];
AFHTTPRequestOperationManager *operationManager=[[AFHTTPRequestOperationManager alloc]initWithBaseURL:url];
//根據(jù)不同的網(wǎng)絡狀態(tài)改變?nèi)プ鱿鄳幚? [operationManager.reachabilityManager setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
switch (status) {
case AFNetworkReachabilityStatusReachableViaWWAN:
[self fasongsuoyou];
break;
case AFNetworkReachabilityStatusReachableViaWiFi:
[self fasongsuoyou];
break;
case AFNetworkReachabilityStatusNotReachable:
[self alert:NSLocalizedString(@"wuwangluo",@"")];
break;
default:
break;
}
}];
//開始監(jiān)控
[operationManager.reachabilityManager startMonitoring];
十三. image轉(zhuǎn)換成data類型
NSData *data=UIImagePNGRepresentation(image);
NSData *data=UIImageJPEGRepresentation(image, 1.0);
十四. 獲取當前時間和時間戳
//當前時間
NSDate * senddate=[NSDate date];
NSDateFormatter *dateformatter=[[NSDateFormatter alloc] init];
[dateformatter setDateFormat:@"YYYY-MM-dd HH:mm:ss"];
NSString * locationString=[dateformatter stringFromDate:senddate];
//當前時間戳
NSDate* dat = [NSDate dateWithTimeIntervalSinceNow:0];
NSTimeInterval a=[dat timeIntervalSince1970];
NSString *timeString = [NSString stringWithFormat:@"%f", a];
long s = [timeString intValue];
十五. 對比時間差
-(int)max:(NSDate *)datatime
{
//創(chuàng)建日期格式化對象
NSDateFormatter *dateFormatter=[[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"YYYY-MM-dd hh:mm:ss"];
NSDate * senddate=[NSDate date];
NSString * locationString=[dateFormatter stringFromDate:senddate];
NSDate *date=[dateFormatter dateFromString:locationString];
//取兩個日期對象的時間間隔:
//這里的NSTimeInterval 并不是對象睡腿,是基本型,其實是double類型片林,是由c定義的:typedef double NSTimeInterval;
NSTimeInterval time=[date timeIntervalSinceDate:datatime];
int days=((int)time)/(3600*24);
return days;
}
十六. 使提示框消失(定時)
[alu dismissWithClickedButtonIndex:0 animated:NO];
十七. 設置self.title的顏色
UIColor * color=[UIColor whiteColor];
NSDictionary * dict=[NSDictionary dictionaryWithObject:color forKey:UITextAttributeTextColor];
self.navigationController.navigationBar.titleTextAttributes = dict;
十八. 請求定位權(quán)限以及定位屬性
//定位管理器
_locationManager=[[CLLocationManager alloc]init];
//如果沒有授權(quán)則請求用戶授權(quán)
if ([CLLocationManager authorizationStatus]==kCLAuthorizationStatusNotDetermined){
[_locationManager requestWhenInUseAuthorization];
}else if([CLLocationManager authorizationStatus]==kCLAuthorizationStatusAuthorizedWhenInUse){
//設置代理
_locationManager.delegate=self;
//設置定位精度
_locationManager.desiredAccuracy=kCLLocationAccuracyBest;
//定位頻率,每隔多少米定位一次
CLLocationDistance distance=10.0;//十米定位一次
_locationManager.distanceFilter=distance;
//啟動跟蹤定位
[_locationManager startUpdatingLocation];
}
十九. 通過經(jīng)緯度計算距離
BOOL JuLi=NO;
CLLocation *orig=[[CLLocation alloc] initWithLatitude:oldlat longitude:oldlong];
CLLocation* dist=[[CLLocation alloc] initWithLatitude:nowlat longitude:nowlong];
CLLocationDistance kilometers=[orig distanceFromLocation:dist];
NSLog(@"距離:%f",kilometers);
if (kilometers>=10) {
JuLi=YES;
}
else{
JuLi=NO;
}
return JuLi;
二十. 彈出效果
/**
* 彈出對話框的動畫
*
* @param changeOutView 要執(zhí)行的view
* @param dur 動畫時長
*/
-(void)exChangeOut:(UIView *)changeOutView dur:(CFTimeInterval)dur{
CAKeyframeAnimation * animation;
animation = [CAKeyframeAnimation animationWithKeyPath:@"transform"];
animation.duration = dur;
//animation.delegate = self;
animation.removedOnCompletion = NO;
animation.fillMode = kCAFillModeForwards;
NSMutableArray *values = [NSMutableArray array];
[values addObject:[NSValue valueWithCATransform3D:CATransform3DMakeScale(0.1, 0.1, 1.0)]];
[values addObject:[NSValue valueWithCATransform3D:CATransform3DMakeScale(1.2, 1.2, 1.0)]];
[values addObject:[NSValue valueWithCATransform3D:CATransform3DMakeScale(0.9, 0.9, 0.9)]];
[values addObject:[NSValue valueWithCATransform3D:CATransform3DMakeScale(1.0, 1.0, 1.0)]];
animation.values = values;
animation.timingFunction = [CAMediaTimingFunction functionWithName: @"easeInEaseOut"];
[changeOutView.layer addAnimation:animation forKey:nil];
}
二十一. 設置TextField左右視圖
-(id)initWithFrame:(CGRect)frame drawingLeft:(UIImageView *)icon drawingRight:(UIButton *)bu{
self = [super initWithFrame:frame];
if (self) {
self.leftView = icon;
self.leftViewMode = UITextFieldViewModeAlways;
self.rightView= bu;
self.rightViewMode=UITextFieldViewModeAlways;
}
return self;
}
-(CGRect)leftViewRectForBounds:(CGRect)bounds{
CGRect iconRect = [super leftViewRectForBounds:bounds];
iconRect.origin.x += 5;// 右偏10
return iconRect;
}
-(CGRect)rightViewRectForBounds:(CGRect)bounds
{
CGRect burect=[super rightViewRectForBounds:bounds];
burect.origin.x +=-10;
return burect;
}
二十二. 常用宏定義
#define PUSH(x) AppDelegate *appdelegate=(AppDelegate *)[UIApplication sharedApplication].delegate;[(UINavigationController*)appdelegate.window.rootViewController pushViewController:x animated:YES];
#define POP AppDelegate *appdelegate=(AppDelegate *)[UIApplication sharedApplication].delegate;[(UINavigationController*)appdelegate.window.rootViewController popViewControllerAnimated:YES];
#define POPROOT OGPAppDelegate *appdelegate=(OGPAppDelegate *)[UIApplication sharedApplication].delegate;[(UINavigationController*)appdelegate.window.rootViewController popToRootViewControllerAnimated:YES];
#define IOS7 ([[UIDevice currentDevice].systemVersion floatValue] >= 7.0f)
#define IPHONE_4INCH ([UIScreen mainScreen].bounds.size.height > 480.0f)
// 隨機顏色
#define RANDOM_COLOR [UIColor colorWithRed:arc4random_uniform(256) / 255.0 green:arc4random_uniform(256) / 255.0 blue:arc4random_uniform(256) / 255.0 alpha:1]
二十三. 獲取版本號提示版本更新
-(void)VersionButton
{
NSString * string=[NSString stringWithContentsOfURL:[NSURL URLWithString:@"http://itunes.apple.com/lookup?id=??????????"] encoding:NSUTF8StringEncoding error:nil];
if (string!=nil && [string length]>0 && [string rangeOfString:@"version"].length==7) {
[self checkenAppUpdate:string];
}
}
-(void)checkenAppUpdate:(NSString *)appinfo
{
NSString * version=[[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleVersion"];
NSString * appInfo1=[appinfo substringFromIndex:[appinfo rangeOfString:@"\"version\":"].location+10];
appInfo1=[[appInfo1 substringToIndex:[appInfo1 rangeOfString:@","].location] stringByReplacingOccurrencesOfString:@"\"" withString:@""];
if (![appInfo1 isEqualToString:version]) {
UIAlertView * alert=[[UIAlertView alloc]initWithTitle:@"" message:[NSString stringWithFormat:@"新版本%@, 已經(jīng)發(fā)布",appInfo1] delegate:self cancelButtonTitle:@"知道了" otherButtonTitles: nil];
alert.delegate=self;
[alert addButtonWithTitle:@"前往更新"];
[alert show];
alert.tag=20;
}
}
-(void)alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex
{
if (buttonIndex==1 & alertView.tag==20) {
NSString * url=@"https://appsto.re/cn/-naScb.i";
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:url]];
}
}
二十四. 獲取設備或APP信息
//返回應用程序名稱
+(NSString *) getAppName{
NSDictionary *infoDictionary = [[NSBundle mainBundle] infoDictionary];
return [infoDictionary objectForKey:@"CFBundleDisplayName"];
}
//返回應用版本號
+(NSString *) getAppVersion{
NSDictionary *infoDictionary = [[NSBundle mainBundle] infoDictionary];
return [infoDictionary objectForKey:@"CFBundleShortVersionString"];
}
+(NSString *) getAppBundleVersion{
NSDictionary *infoDictionary = [[NSBundle mainBundle] infoDictionary];
return [infoDictionary objectForKey:@"CFBundleVersion"];
}
//設備型號
+(NSString *) getSystemName{
return [[UIDevice currentDevice] systemName];
}
//設備版本號
+(NSString *) getSystemVersion{
return [[UIDevice currentDevice] systemVersion];
}
二十五. 內(nèi)存泄漏分析
靜態(tài)分析內(nèi)存泄露 使用Xcode自帶的Analyze功能(Product-> Analyze)(Shift + Command + B)譬涡,對代碼進行靜態(tài)分析,對于內(nèi)存泄露(Potential Memory Leak), 未使用局部變量(dead store)料皇,邏輯錯誤(Logic Flaws)以及API使用問題(API-usage)等明確的展示出來谓松。 靜態(tài)分析的內(nèi)存泄露情況比較簡單星压,開發(fā)者都能很快的解決。這里不做贅述鬼譬。
動態(tài)分析內(nèi)存泄露 使用Xcode自帶的Profile功能(Product-> Profile)(Command + i)彈出工具框娜膘,選擇Leaks打開,選擇運行設備點左上角的Record錄制按鈕优质,項目就會在已選好的設備上運行竣贪,并開始錄制內(nèi)存檢測情況。選Leaks查看泄露情況巩螃,在Leaks的詳細菜單Details選項里選調(diào)用樹Call Tree贾富,可查看所有內(nèi)存泄露發(fā)生在哪些地方。再在右側(cè)的齒輪設置-Call Tree-勾選Hide System Libraries牺六,則可直接看內(nèi)存泄露發(fā)生的函數(shù)名颤枪、方法名。點擊函數(shù)名淑际、方法名畏纲,可直接跳到函數(shù)方法的細節(jié),可以看到哪一句代碼出現(xiàn)了內(nèi)存泄露春缕,以及泄露了多少內(nèi)存盗胀。
接下來就要回到Xcode,找到出現(xiàn)內(nèi)存泄露的函數(shù)方法锄贼,仔細分析如何出現(xiàn)的內(nèi)存泄露; 一般使用ARC票灰,按照上面一提到的內(nèi)存理解和編碼習慣是不會出現(xiàn)內(nèi)存泄露的。但我們在開發(fā)過程中宅荤,經(jīng)常要使用第三方的一些類庫屑迂,特別是涉及到加密的類庫,用c或c++來編碼的加密解密方法冯键,會出現(xiàn)內(nèi)存泄露惹盼。此時,我們要明白這些內(nèi)存分配惫确,需要手動釋放手报。要一步一步看,哪里分配了內(nèi)存改化,在使用完之后一定要記得釋放free它掩蛤。
二十六. block循環(huán)利用導致內(nèi)存泄漏
A *a = [[A alloc] init];
a.finishBlock = ^(NSDictionary paraments){ [a doSomething]; }; 對于這種在block塊里引用對象a的情況,要在創(chuàng)建對象a時加修飾符block來防止循環(huán)引用陈肛。
block A *a = [[A alloc] init];
a.finishBlock = ^(NSDictionary paraments){ [a doSomething]; }; 或
A __block a = [[A alloc] init]; a.finishBlock = ^(NSDictionary paraments){ [a doSomething]; };
或者揍鸟,需要在block中調(diào)用用self的方法、屬性燥爷、變量時蜈亩,可以這樣寫
__weak typeof(self) weakSelf = self;
在block中使用weakSelf。
__weak typeof(self) weakSelf = self;
[b doSomethingWithFinishBlock:^{ weakSelf.text = @"內(nèi)存檢測"; [weakSelf doSomething]; }];
二十七. label 的空格屬性和局部字段顏色
設置 label 的 autoresizingMask 為 NO ,可以使用空格間隔字符串!
NSMutableAttributedString *hintString=[[NSMutableAttributedString alloc]initWithString:@"點擊注冊按鈕服務協(xié)議"];
//獲取要調(diào)整顏色的文字位置,調(diào)整顏色
NSRange range1=[[hintString string]rangeOfString:@"注冊"];
[hintString addAttribute:NSForegroundColorAttributeName value:[UIColor greenColor] range:range1];
NSRange range2=[[hintString string]rangeOfString:@"服務協(xié)議"];
[hintString addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:range2];
hintLabel.attributedText=hintString;
二十八. 過濾特殊字符
// 定義一個特殊字符的集合
NSCharacterSet *set = [NSCharacterSet characterSetWithCharactersInString:
@"@/:前翎;()¥「」"稚配、[]{}#%-*+=_\\|~<>$€^?'@#$%^&*()_+'\""];
// 過濾字符串的特殊字符
NSString *newString = [trimString stringByTrimmingCharactersInSet:set];
二十九. 設置滑動的時候隱藏 navigationbar
第1種:
navigationController.hidesBarsOnSwipe = Yes
第2種:
//1.當我們的手離開屏幕時候隱藏
- (void)scrollViewWillEndDragging:(UIScrollView *)scrollView withVelocity:(CGPoint)velocity targetContentOffset:(inout CGPoint *)targetContentOffset
{
if(velocity.y > 0)
{
[self.navigationController setNavigationBarHidden:YES animated:YES];
} else {
[self.navigationController setNavigationBarHidden:NO animated:YES];
}
}
velocity.y這個量,在上滑和下滑時港华,變化極械来ā(小數(shù)),但是因為方向不同立宜,有正負之分冒萄,這就很好處理 了。
三十. 屏幕截圖
// 1. 開啟一個與圖片相關(guān)的圖形上下文
UIGraphicsBeginImageContextWithOptions(self.view.bounds.size,NO,0.0);
// 2. 獲取當前圖形上下文
CGContextRef ctx = UIGraphicsGetCurrentContext();
// 3. 獲取需要截取的view的layer
[self.view.layer renderInContext:ctx];
// 4. 從當前上下文中獲取圖片
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
// 5. 關(guān)閉圖形上下文
UIGraphicsEndImageContext();
// 6. 把圖片保存到相冊
UIImageWriteToSavedPhotosAlbum(image, nil, nil, nil);
三十一. 去掉 tabbar 和 navgationbar 的黑線
//去掉tabBar頂部線條
CGRect rect = CGRectMake(0, 0, 1, 1);
UIGraphicsBeginImageContext(rect.size);
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSetFillColorWithColor(context, [[UIColor clearColor] CGColor]);
CGContextFillRect(context, rect);
UIImage *img = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
[self.tabBar setBackgroundImage:img];
[self.tabBar setShadowImage:img];
//[self.navigationController.navigationBar setBackgroundImage:img];
//self.navigationController.navigationBar.shadowImage = ima;
self.tabBar.backgroundColor = SLIVERYCOLOR;
三十二. 判斷字符串中是否含有中文
-(BOOL)isChinese:(NSString *)str{
NSString *match=@"(^[\u4e00-\u9fa5]+$)";
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF matches %@", match];
return [predicate evaluateWithObject:str];
}
三十三. 解決父視圖和子視圖的手勢沖突問題
/** 解決手勢沖突 */
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch{
if ([touch.view isDescendantOfView:cicView]) {
return NO;
}
return YES;
}
三十四. 獲取當前連接的Wi-Fi的名稱
NSString *wifiName = @"Not Found";
CFArrayRef myArray = CNCopySupportedInterfaces();
if (myArray != nil) {
CFDictionaryRef myDict = CNCopyCurrentNetworkInfo(CFArrayGetValueAtIndex(myArray, 0));
if (myDict != nil) {
NSDictionary *dict = (NSDictionary*)CFBridgingRelease(myDict);
wifiName = [dict valueForKey:@"SSID"];
}
}
三十五. 跨控制器跳轉(zhuǎn)返回
for (UIViewController *controller in self.navigationController.viewControllers) {
if ([controller isKindOfClass:[@“你要返回的控制器類名” class]]) {
[self.navigationController popToViewController:controller animated:YES];
}
}
三十六. layer.cornerRadius 圓角流暢性的優(yōu)化
loginBtn.layer.rasterizationScale = [UIScreen mainScreen].scale;
三十七. 導航欄和下方視圖間隔距離消失
self.automaticallyAdjustsScrollViewInsets=YES;
三十八. 毛玻璃效果(ios8.0以后的版本)
UIVisualEffectView *visualEffectView = [[UIVisualEffectView alloc] initWithEffect:[UIBlurEffect effectWithStyle:UIBlurEffectStyleLight]];
visualEffectView.frame = CGRectMake(0, 0, 320*[FlexibleFrame ratio], 180*[FlexibleFrame ratio]);
visualEffectView.alpha = 1.0;
三十九. 移動工程不需要配置路徑
創(chuàng)建.pch文件時 , BuildSetting 中的 Prefix Header 中的路徑開頭可以寫 $(SRCROOT)/工程地址, 這樣寫的好處可以使你的挪動代碼不用手動更換路徑!
四十. 判斷兩個數(shù)組是否相同
NSArray *array1 = [NSArray arrayWithObjects:@"a", @"b", @"c", nil];
NSArray *array2 = [NSArray arrayWithObjects:@"d", @"a", @"c", nil];
bool bol = false;
//創(chuàng)建倆新的數(shù)組
NSMutableArray *oldArr = [NSMutableArray arrayWithArray:array1];
NSMutableArray *newArr = [NSMutableArray arrayWithArray:array2];
//對數(shù)組1排序橙数。
[oldArr sortUsingComparator:^NSComparisonResult(id obj1, id obj2){
return obj1 > obj2;
}];
//對數(shù)組2排序尊流。
[newArr sortUsingComparator:^NSComparisonResult(id obj1, id obj2){
return obj1 > obj2;
}];
if (newArr.count == oldArr.count) {
bol = true;
for (int16_t i = 0; i < oldArr.count; i++) {
id c1 = [oldArr objectAtIndex:i];
id newc = [newArr objectAtIndex:i];
if (![newc isEqualToString:c1]) {
bol = false;
break;
}
}
}
if (bol) {
NSLog(@" ------------- 兩個數(shù)組的內(nèi)容相同!");
}
else {
NSLog(@"-=-------------兩個數(shù)組的內(nèi)容不相同灯帮!");
}
四十一. block
對于block崖技,都應該使用copy來聲明,原因是block來捕獲上下文的信息 官方文檔
四十二. 使應用在后臺運行
- (void)applicationDidEnterBackground:(UIApplication *)application
{
__block UIBackgroundTaskIdentifier bgTask = UIBackgroundTaskInvalid;
bgTask = [application beginBackgroundTaskWithExpirationHandler:^{
dispatch_async(dispatch_get_main_queue(), ^{
if (bgTask != UIBackgroundTaskInvalid) {
bgTask = UIBackgroundTaskInvalid;
}
});
}];
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
dispatch_async(dispatch_get_main_queue(), ^{
if (bgTask != UIBackgroundTaskInvalid) {
bgTask = UIBackgroundTaskInvalid;
}
});
});
}
但其實不是應用一直在運行钟哥。
四十三. 計算一段NSString在視圖中渲染出來的尺寸
+ (CGSize)sizeOfString:(NSString *)textString font:(UIFont *)font bound:(CGSize)bound {
NSMutableParagraphStyle * paragraphStyle = [[NSMutableParagraphStyle alloc] init];
paragraphStyle.lineBreakMode = NSLineBreakByWordWrapping;
paragraphStyle.alignment = NSTextAlignmentLeft;
if (font == nil) {
font = [UIFont systemFontOfSize:[UIFont systemFontSize]];
}
NSDictionary * attributes = @{NSFontAttributeName : font,
NSParagraphStyleAttributeName : paragraphStyle};
NSAttributedString* attributedString = [[NSAttributedString alloc] initWithString:textString attributes:attributes];
return [TTTAttributedLabel sizeThatFitsAttributedString:attributedString
withConstraints:CGSizeMake(bound.width, 999)
limitedToNumberOfLines:0];
}
四十四. 獲取相應的字體類型名
for(NSString *fontfamilyname in [UIFont familyNames])
{
NSLog(@"Family:'%@'",fontfamilyname);
for(NSString *fontName in [UIFont fontNamesForFamilyName:fontfamilyname])
{
NSLog(@"\tfont:'%@'",fontName);
}
NSLog(@"~~~~~~~~");
}
四十五. Masonry和SVProgreaaHUD需要注意
使用Masonry約束TTTAttributedLabel的時候迎献,初始化TTTAttributedLabel需要設置frame為CGRectZero,否則約束會不生效腻贰。
SVProgressHUD如果要自定義一些屬性吁恍,比如loading狀態(tài)轉(zhuǎn)圈的顏色,必須先設置style為SVProgressHUDStyleCustom播演,這樣自定義的狀態(tài)才會生效冀瓦。
四十六. 打印View所有子視圖
po [[self view]recursiveDescription]
四十七. layoutSubviews調(diào)用的調(diào)用時機
* 當視圖第一次顯示的時候會被調(diào)用
* 當這個視圖顯示到屏幕上了,點擊按鈕
* 添加子視圖也會調(diào)用這個方法
* 當本視圖的大小發(fā)生改變的時候是會調(diào)用的
* 當子視圖的frame發(fā)生改變的時候是會調(diào)用的
* 當刪除子視圖的時候是會調(diào)用的
四十八. UIImageView填充模式
@"UIViewContentModeScaleToFill", // 拉伸自適應填滿整個視圖
@"UIViewContentModeScaleAspectFit", // 自適應比例大小顯示
@"UIViewContentModeScaleAspectFill", // 原始大小顯示
@"UIViewContentModeRedraw", // 尺寸改變時重繪
@"UIViewContentModeCenter", // 中間
@"UIViewContentModeTop", // 頂部
@"UIViewContentModeBottom", // 底部
@"UIViewContentModeLeft", // 中間貼左
@"UIViewContentModeRight", // 中間貼右
@"UIViewContentModeTopLeft", // 貼左上
@"UIViewContentModeTopRight", // 貼右上
@"UIViewContentModeBottomLeft", // 貼左下
@"UIViewContentModeBottomRight", // 貼右下
四十九. MRC和ARC混編設置方式
在XCode中targets的build phases選項下Compile Sources下選擇 不需要arc編譯的文件
雙擊輸入 -fno-objc-arc 即可
MRC工程中也可以使用ARC的類,方法如下:
在XCode中targets的build phases選項下Compile Sources下選擇要使用arc編譯的文件
雙擊輸入 -fobjc-arc 即可
五十. 解決tableview的分割線短一截
-(void)viewDidLayoutSubviews{
if ([self.tableView respondsToSelector:@selector(setSeparatorInset:)])
{
[self.tableView setSeparatorInset:UIEdgeInsetsMake(0,0,0,0)];
}
if ([self.tableView respondsToSelector:@selector(setLayoutMargins:)])
{
[self.tableView setLayoutMargins:UIEdgeInsetsMake(0,0,0,0)];
}
}
-(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath{
if ([cell respondsToSelector:@selector(setSeparatorInset:)])
{
[cell setSeparatorInset:UIEdgeInsetsZero];
}
if ([cell respondsToSelector:@selector(setLayoutMargins:)])
{
[cell setLayoutMargins:UIEdgeInsetsZero];
}
}
五十一. 修改textFieldplaceholder字體顏色和大小
textField.placeholder = @"username is in here!";
[textField setValue:[UIColor redColor] forKeyPath:@"_placeholderLabel.textColor"];
[textField setValue:[UIFont boldSystemFontOfSize:16] forKeyPath:@"_placeholderLabel.font"];
五十二. 修改狀態(tài)欄字體顏色
只能設置兩種顏色写烤,黑色和白色咕幻,系統(tǒng)默認黑色
設置為白色方法:
(1)在plist里面添加Status bar style,值為UIStatusBarStyleLightContent(白色)或UIStatusBarStyleDefault(黑 色)
(2)在Info.plist中設置UIViewControllerBasedStatusBarAppearance 為NO
五十三.調(diào)用相機后狀態(tài)欄消失
[[UIApplication sharedApplication] setStatusBarHidden:NO animated:NO];
[[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleBlackTranslucent animated:YES];
五十四. 修改UIAlertController字體顏色
//修改title
NSMutableAttributedString *alertControllerStr = [[NSMutableAttributedString alloc] initWithString:@"提示"];
[alertControllerStr addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:NSMakeRange(0, 2)];
[alertControllerStr addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:17] range:NSMakeRange(0, 2)];
if (alertController valueForKey:@"attributedTitle") {
[alertController setValue:alertControllerStr forKey:@"attributedTitle"];
}
//修改message
NSMutableAttributedString *alertControllerMessageStr = [[NSMutableAttributedString alloc] initWithString:@"提示內(nèi)容"];
[alertControllerMessageStr addAttribute:NSForegroundColorAttributeName value:[UIColor greenColor] range:NSMakeRange(0, 4)];
[alertControllerMessageStr addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:20] range:NSMakeRange(0, 4)];
if (alertController valueForKey:@"attributedMessage") {
[alertController setValue:alertControllerMessageStr forKey:@"attributedMessage"];
}
//修改按鈕字體顏色
UIAlertAction *defaultAction = [UIAlertAction actionWithTitle:@"Default" style:UIAlertActionStyleDefault handler:nil];
[alertController addAction:defaultAction];
if (cancelAction valueForKey:@"titleTextColor") {
[cancelAction setValue:[UIColor redColor] forKey:@"titleTextColor"];
}
五十五. 使用鑰匙串保存設備唯一ID
下載并倒入SSKeyChain的.h和.m文件顶霞,并添加Security.framework框架
+ (NSString *)getDeviceId
{
NSString * currentDeviceUUIDStr = [SSKeychain passwordForService:@" "account:@"uuid"];
if (currentDeviceUUIDStr == nil || [currentDeviceUUIDStr isEqualToString:@""])
{
NSUUID * currentDeviceUUID = [UIDevice currentDevice].identifierForVendor;
currentDeviceUUIDStr = currentDeviceUUID.UUIDString;
currentDeviceUUIDStr = [currentDeviceUUIDStr stringByReplacingOccurrencesOfString:@"-" withString:@""];
currentDeviceUUIDStr = [currentDeviceUUIDStr lowercaseString];
[SSKeychain setPassword: currentDeviceUUIDStr forService:@" "account:@"uuid"];
}
return currentDeviceUUIDStr;
}
五十六. 獲取設備型號
引入頭文件
include <sys/types.h>
include <sys/sysctl.h>
+ (NSString *)getCurrentDeviceModel
{
int mib[2];
size_t len;
char *machine;
mib[0] = CTL_HW;
mib[1] = HW_MACHINE;
sysctl(mib, 2, NULL, &len, NULL, 0);
machine = malloc(len);
sysctl(mib, 2, machine, &len, NULL, 0);
NSString *platform = [NSString stringWithCString:machine encoding:NSASCIIStringEncoding];
free(machine);
// iPhone
if ([platform isEqualToString:@"iPhone1,1"]) return @"iPhone2G";
if ([platform isEqualToString:@"iPhone1,2"]) return @"iPhone3G";
if ([platform isEqualToString:@"iPhone2,1"]) return @"iPhone3GS";
if ([platform isEqualToString:@"iPhone3,1"]) return @"iPhone4";
if ([platform isEqualToString:@"iPhone3,2"]) return @"iPhone4";
if ([platform isEqualToString:@"iPhone3,3"]) return @"iPhone4";
if ([platform isEqualToString:@"iPhone4,1"]) return @"iPhone4S";
if ([platform isEqualToString:@"iPhone5,1"]) return @"iPhone5";
if ([platform isEqualToString:@"iPhone5,2"]) return @"iPhone5";
if ([platform isEqualToString:@"iPhone5,3"]) return @"iPhone5c";
if ([platform isEqualToString:@"iPhone5,4"]) return @"iPhone5c";
if ([platform isEqualToString:@"iPhone6,1"]) return @"iPhone5s";
if ([platform isEqualToString:@"iPhone6,2"]) return @"iPhone5s";
if ([platform isEqualToString:@"iPhone7,2"]) return @"iPhone6";
if ([platform isEqualToString:@"iPhone7,1"]) return @"iPhone6Plus";
if ([platform isEqualToString:@"iPhone8,1"]) return @"iPhone6s";
if ([platform isEqualToString:@"iPhone8,2"]) return @"iPhone6sPlus";
if ([platform isEqualToString:@"iPhone8,3"]) return @"iPhoneSE";
if ([platform isEqualToString:@"iPhone8,4"]) return @"iPhoneSE";
if ([platform isEqualToString:@"iPhone9,1"]) return @"iPhone7";
if ([platform isEqualToString:@"iPhone9,2"]) return @"iPhone7Plus";
//iPod Touch
if ([platform isEqualToString:@"iPod1,1"]) return @"iPodTouch";
if ([platform isEqualToString:@"iPod2,1"]) return @"iPodTouch2G";
if ([platform isEqualToString:@"iPod3,1"]) return @"iPodTouch3G";
if ([platform isEqualToString:@"iPod4,1"]) return @"iPodTouch4G";
if ([platform isEqualToString:@"iPod5,1"]) return @"iPodTouch5G";
if ([platform isEqualToString:@"iPod7,1"]) return @"iPodTouch6G";
//iPad
if ([platform isEqualToString:@"iPad1,1"]) return @"iPad";
if ([platform isEqualToString:@"iPad2,1"]) return @"iPad2";
if ([platform isEqualToString:@"iPad2,2"]) return @"iPad2";
if ([platform isEqualToString:@"iPad2,3"]) return @"iPad2";
if ([platform isEqualToString:@"iPad2,4"]) return @"iPad2";
if ([platform isEqualToString:@"iPad3,1"]) return @"iPad3";
if ([platform isEqualToString:@"iPad3,2"]) return @"iPad3";
if ([platform isEqualToString:@"iPad3,3"]) return @"iPad3";
if ([platform isEqualToString:@"iPad3,4"]) return @"iPad4";
if ([platform isEqualToString:@"iPad3,5"]) return @"iPad4";
if ([platform isEqualToString:@"iPad3,6"]) return @"iPad4";
//iPad Air
if ([platform isEqualToString:@"iPad4,1"]) return @"iPadAir";
if ([platform isEqualToString:@"iPad4,2"]) return @"iPadAir";
if ([platform isEqualToString:@"iPad4,3"]) return @"iPadAir";
if ([platform isEqualToString:@"iPad5,3"]) return @"iPadAir2";
if ([platform isEqualToString:@"iPad5,4"]) return @"iPadAir2";
//iPad mini
if ([platform isEqualToString:@"iPad2,5"]) return @"iPadmini1G";
if ([platform isEqualToString:@"iPad2,6"]) return @"iPadmini1G";
if ([platform isEqualToString:@"iPad2,7"]) return @"iPadmini1G";
if ([platform isEqualToString:@"iPad4,4"]) return @"iPadmini2";
if ([platform isEqualToString:@"iPad4,5"]) return @"iPadmini2";
if ([platform isEqualToString:@"iPad4,6"]) return @"iPadmini2";
if ([platform isEqualToString:@"iPad4,7"]) return @"iPadmini3";
if ([platform isEqualToString:@"iPad4,8"]) return @"iPadmini3";
if ([platform isEqualToString:@"iPad4,9"]) return @"iPadmini3";
if ([platform isEqualToString:@"iPad5,1"]) return @"iPadmini4";
if ([platform isEqualToString:@"iPad5,2"]) return @"iPadmini4";
if ([platform isEqualToString:@"i386"]) return @"iPhoneSimulator";
if ([platform isEqualToString:@"x86_64"]) return @"iPhoneSimulator";
return platform;
}
五十七. 減少發(fā)布之后過多的NSLog帶來的性能影響
#if defined(DEBUG)||defined(_DEBUG)
NSLog(@"測試代碼");
NSLog(@"Test Coding");
#endif
五十八. 去掉字符串的前后空格(基本用在textfield)
NSString *textName = [self.nameCell.textField.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
五十九. 截取字符串到指定字符的位置
NSString *string = @"abcdefghijklmn";
NSRange range = [string rangeOfString:@"h"];
string = [string substringToIndex:range.location];
六十. 獲取label的行數(shù)和每行的內(nèi)容
- (NSArray *)getLinesArrayOfStringInLabel:(UILabel *)label{
NSString *text = [label text];
UIFont *font = [label font];
CGRect rect = [label frame];
CTFontRef myFont = CTFontCreateWithName(( CFStringRef)([font fontName]), [font pointSize], NULL);
NSMutableAttributedString *attStr = [[NSMutableAttributedString alloc] initWithString:text];
[attStr addAttribute:(NSString *)kCTFontAttributeName value:(__bridge id)myFont range:NSMakeRange(0, attStr.length)];
CFRelease(myFont);
CTFramesetterRef frameSetter = CTFramesetterCreateWithAttributedString(( CFAttributedStringRef)attStr);
CGMutablePathRef path = CGPathCreateMutable();
CGPathAddRect(path, NULL, CGRectMake(0,0,rect.size.width,100000));
CTFrameRef frame = CTFramesetterCreateFrame(frameSetter, CFRangeMake(0, 0), path, NULL);
NSArray *lines = ( NSArray *)CTFrameGetLines(frame);
NSMutableArray *linesArray = [[NSMutableArray alloc]init];
for (id line in lines) {
CTLineRef lineRef = (__bridge CTLineRef )line;
CFRange lineRange = CTLineGetStringRange(lineRef);
NSRange range = NSMakeRange(lineRange.location, lineRange.length);
NSString *lineString = [text substringWithRange:range];
CFAttributedStringSetAttribute((CFMutableAttributedStringRef)attStr, lineRange, kCTKernAttributeName, (CFTypeRef)([NSNumber numberWithFloat:0.0]));
CFAttributedStringSetAttribute((CFMutableAttributedStringRef)attStr, lineRange, kCTKernAttributeName, (CFTypeRef)([NSNumber numberWithInt:0.0]));
//NSLog(@"''''''''''''''''''%@",lineString);
[linesArray addObject:lineString];
}
CGPathRelease(path);
CFRelease( frame );
CFRelease(frameSetter);
return (NSArray *)linesArray;
}
六十一.鍵盤透明
[UITextField alloc].keyboardAppearance = UIKeyboardAppearanceAlert;
六十二.狀態(tài)欄的網(wǎng)絡活動風火輪是否旋轉(zhuǎn),默認為NO
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
六十三.開啟右滑返回
self.navigationController.interactivePopGestureRecognizer.delegate = nil;
六十四.MD5加密
#import "NSString+MD5.h"
#import <CommonCrypto/CommonCrypto.h>
- (NSString *)stringToMD5:(NSString *)str
{
//1.首先將字符串轉(zhuǎn)換成UTF-8編碼, 因為MD5加密是基于C語言的,所以要先把字符串轉(zhuǎn)化成C語言的字符串
const char *fooData = [str UTF8String];
//2.然后創(chuàng)建一個字符串數(shù)組,接收MD5的值
unsigned char result[CC_MD5_DIGEST_LENGTH];
//3.計算MD5的值, 這是官方封裝好的加密方法:把我們輸入的字符串轉(zhuǎn)換成16進制的32位數(shù),然后存儲到result中
CC_MD5(fooData, (CC_LONG)strlen(fooData), result);
/**
第一個參數(shù):要加密的字符串
第二個參數(shù): 獲取要加密字符串的長度
第三個參數(shù): 接收結(jié)果的數(shù)組
*/
//4.創(chuàng)建一個字符串保存加密結(jié)果
NSMutableString *saveResult = [NSMutableString string];
//5.從result 數(shù)組中獲取加密結(jié)果并放到 saveResult中
for (int i = 0; i < CC_MD5_DIGEST_LENGTH; i++) {
[saveResult appendFormat:@"%02x", result];
}
/*
x表示十六進制肄程,%02X 意思是不足兩位將用0補齊,如果多余兩位則不影響
NSLog("%02X", 0x888); //888
NSLog("%02X", 0x4); //04
*/
return saveResult;
}
六十五.導航欄返回按鈕顏色設置 及 文字變成<
-(void)UIBarButtonBackItemSet
{
[[UIBarButtonItem appearance] setBackButtonTitlePositionAdjustment:UIOffsetMake(0, -60)
forBarMetrics:UIBarMetricsDefault];
self.navigationController.navigationBar.barStyle = UIStatusBarStyleDefault;
[self.navigationController.navigationBar setTintColor:[UIColor whiteColor]];
}
六十六.字符串中包含雙引號和反斜杠處理
NSString * testStr = @"你好选浑,\"你好\"";
NSLog(@"%@",testStr);
//輸出結(jié)果為:你好蓝厌,"你好"
NSString * testStr = @"不好,\\不好\\\\";
NSLog(@"%@",testStr);
//輸出結(jié)果為:不好古徒,\不好\\
##待續(xù)M靥帷!