版權(quán)聲明:本文為博主原創(chuàng)文章,未經(jīng)博主允許不得轉(zhuǎn)載。

iPhone Size:
| 手機型號 | 屏幕尺寸 |
|---|---|
| iPhone 4 4s | 320 * 480 |
| iPhone 5 5s | 320 * 568 |
| iPhone 6 6s | 375 * 667 |
| iphone 6 plus 6s plus | 414 * 736 |
1.判斷郵箱格式是否正確的代碼:
//利用正則表達式驗證
-(BOOL)isValidateEmail:(NSString *)email
{
NSString *emailRegex = @"[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}";
NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES%@",emailRegex];
return [emailTest evaluateWithObject:email];
}
2.圖片壓縮
用法:UIImage *yourImage= [self imageWithImageSimple:image scaledToSize:CGSizeMake(210.0, 210.0)];
//壓縮圖片
- (UIImage*)imageWithImageSimple:(UIImage*)image scaledToSize:(CGSize)newSize
{
// 創(chuàng)建一個圖形文本
UIGraphicsBeginImageContext(newSize);
//畫出新文本的尺寸
// new size
[image drawInRect:CGRectMake(0,0,newSize.width,newSize.height)];
//從文本上得到一個新的圖片
UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();
// 結(jié)束編輯文本
UIGraphicsEndImageContext();
// Return the new image.
return newImage;
}
3.親測可用的圖片上傳代碼
//按鈕響應(yīng)事件
- (IBAction)uploadButton:(id)sender {
UIImage *image = [UIImage imageNamed:@"1.jpg"]; //圖片名
NSData *imageData = UIImageJPEGRepresentation(image,0.5);//壓縮比例
NSLog(@"字節(jié)數(shù):%i",[imageData length]);
// post url
NSString *urlString = @"http://192.168.1.113:8090/text/UploadServlet";
//服務(wù)器地址
// setting up the request object now
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init] ;
[request setURL:[NSURL URLWithString:urlString]];
[request setHTTPMethod:@"POST"];
//
NSString *boundary = [NSString stringWithString:@"---------------------------14737809831466499882746641449"];
NSString *contentType = [NSString stringWithFormat:@"multipart/form-data;boundary=%@",boundary];
[request addValue:contentType forHTTPHeaderField: @"Content-Type"];
//
NSMutableData *body = [NSMutableData data];
[body appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithString:@"Content-Disposition:form-data; name=\"userfile\"; filename=\"2.png\"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]]; //上傳上去的圖片名字
[body appendData:[[NSString stringWithString:@"Content-Type: application/octet-stream\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[NSData dataWithData:imageData]];
[body appendData:[[NSString stringWithFormat:@"\r\n--%@--\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[request setHTTPBody:body];
// NSLog(@"1-body:%@",body);
NSLog(@"2-request:%@",request);
NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
NSString *returnString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];
NSLog(@"3-測試輸出:%@",returnString);
4.對圖庫的操作
//選擇相冊:
UIImagePickerControllerSourceTypesourceType=UIImagePickerControllerSourceTypeCamera;
if (![UIImagePickerControllerisSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera])
{
sourceType=UIImagePickerControllerSourceTypePhotoLibrary;
}
UIImagePickerController * picker = [[UIImagePickerControlleralloc]init];
picker.delegate = self;
picker.allowsEditing = YES;
picker.sourceType = sourceType;
[self presentModalViewController:picker animated:YES];
//選擇完畢:
-(void)imagePickerController:(UIImagePickerController*)pickerdidFinishPickingMediaWithInfo:(NSDictionary *)info
{
[picker dismissModalViewControllerAnimated:YES];
UIImage * image=[info objectForKey:UIImagePickerControllerEditedImage];
[self performSelector:@selector(selectPic:) withObject:imageafterDelay:0.1];
}
-(void)selectPic:(UIImage*)image
{
NSLog(@"image%@",image);
imageView = [[UIImageView alloc] initWithImage:image];
imageView.frame = CGRectMake(0, 0, image.size.width, image.size.height);
[self.viewaddSubview:imageView];
[self performSelectorInBackground:@selector(detect:) withObject:nil];
}
//detect為自己定義的方法,編輯選取照片后要實現(xiàn)的效果
//取消選擇:
-(void)imagePickerControllerDIdCancel:(UIImagePickerController*)picker
{
[picker dismissModalViewControllerAnimated:YES];
}
5.創(chuàng)建一個UIBarButtonItem右邊按鈕
UIBarButtonItem *rightButton = [[UIBarButtonItem alloc] initWithTitle:@"右邊" style:UIBarButtonItemStyleDone target:self action:@selector(clickRightButton)];
[self.navigationItem setRightBarButtonItem:rightButton];
6.設(shè)置navigationBar隱藏
self.navigationController.navigationBarHidden = YES;//```
7.iOS開發(fā)之UIlabel多行文字自動換行 (自動折行)
UIView *footerView = [[UIView alloc]initWithFrame:CGRectMake(10, 100, 300, 180)];
UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(10, 100, 300, 150)];
label.text = @"Hello world! Hello world!Hello world! Hello world! Hello world! Hello world! Hello world! Hello world!Hello world! Hello world! Hello world! Hello world! Hello world! Helloworld!";
//自動折行設(shè)置
label.lineBreakMode = UILineBreakModeWordWrap;
label.numberOfLines = 0;```
8.代碼生成button
CGRect frame = CGRectMake(0, 400, 72.0, 37.0);
UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
button.frame = frame;
[button setTitle:@"新添加的按鈕" forState: UIControlStateNormal];
button.backgroundColor = [UIColor clearColor];
button.tag = 2000;
[button addTarget:self action:@selector(buttonClicked:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:button];```
9.讓某個控件在View的中心位置顯示:
(某個控件,比如label,View)label.center = self.view.center;```
10.好看的文字處理
以tableView中cell的textLabel為例子:
cell.backgroundColor = [UIColorscrollViewTexturedBackgroundColor];
//設(shè)置文字的字體
cell.textLabel.font = [UIFont fontWithName:@"AmericanTypewriter" size:100.0f];
//設(shè)置文字的顏色
cell.textLabel.textColor = [UIColor orangeColor];
//設(shè)置文字的背景顏色
cell.textLabel.shadowColor = [UIColor whiteColor];
//設(shè)置文字的顯示位置
cell.textLabel.textAlignment = UITextAlignmentCenter;```
11. 隱藏Status Bar
讀者可能知道一個簡易的方法,那就是在程序的viewDidLoad中加入
[[UIApplication sharedApplication]setStatusBarHidden:YES animated:NO];```
- 更改AlertView背景
UIAlertView *theAlert = [[[UIAlertViewalloc] initWithTitle:@"Atention"
message: @"I'm a Chinese!"
delegate:nil
cancelButtonTitle:@"Cancel"
otherButtonTitles:@"Okay",nil] autorelease];
[theAlert show];
UIImage *theImage = [UIImageimageNamed:@"loveChina.png"];
theImage = [theImage stretchableImageWithLeftCapWidth:0topCapHeight:0];
CGSize theSize = [theAlert frame].size;
UIGraphicsBeginImageContext(theSize);
[theImage drawInRect:CGRectMake(5, 5, theSize.width-10, theSize.height-20)];//這個地方的大小要自己調(diào)整,以適應(yīng)alertview的背景顏色的大小。
theImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
theAlert.layer.contents = (id)[theImage CGImage];```
13.鍵盤透明
textField.keyboardAppearance = UIKeyboardAppearanceAlert;```
14.狀態(tài)欄的網(wǎng)絡(luò)活動風火輪是否旋轉(zhuǎn)
[UIApplication sharedApplication].networkActivityIndicatorVisible,默認值是NO。```
15.截取屏幕圖片
//創(chuàng)建一個基于位圖的圖形上下文并指定大小為CGSizeMake(200,400)
UIGraphicsBeginImageContext(CGSizeMake(200,400));
//renderInContext 呈現(xiàn)接受者及其子范圍到指定的上下文
[self.view.layer renderInContext:UIGraphicsGetCurrentContext()];
//返回一個基于當前圖形上下文的圖片
UIImage *aImage = UIGraphicsGetImageFromCurrentImageContext();
//移除棧頂?shù)幕诋斍拔粓D的圖形上下文
UIGraphicsEndImageContext();
//以png格式返回指定圖片的數(shù)據(jù)
imageData = UIImagePNGRepresentation(aImage);```
16.更改cell選中的背景
UIView *myview = [[UIView alloc] init];
myview.frame = CGRectMake(0, 0, 320, 47);
myview.backgroundColor = [UIColorcolorWithPatternImage:[UIImage imageNamed:@"0006.png"]];
cell.selectedBackgroundView = my view;```
17.能讓圖片適應(yīng)框的大小(沒有確認)
NSString*imagePath = [[NSBundle mainBundle] pathForResource:@"XcodeCrash"ofType:@"png"];
UIImage *image = [[UIImage alloc]initWithContentsOfFile:imagePath];
UIImage *newImage= [image transformWidth:80.f height:240.f];
UIImageView *imageView = [[UIImageView alloc]initWithImage:newImage];
[newImagerelease];
[image release];
[self.view addSubview:imageView];```
18.如果只是想把當前頁面的狀態(tài)欄隱藏的話,直接用下面的代碼就可以了
[[UIApplication sharedApplication] setStatusBarHidden:TRUE];```
19. 如果是想把整個應(yīng)用程序的狀態(tài)欄都隱藏掉,操作如下:
在info.plist上添加一項:Status bar is initially hidden,value為YES;
完后在MainAppDelegate.mm的- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions方法里面加上如下一句就可以了:
[[UIApplication sharedApplication]setStatusBarHidden:YES withAnimation:UIStatusBarAnimationFade];```
20.增強版NSLog
//A better version of NSLog
define NSLog(format, ...) do { \
fprintf(stderr, "<%s : %d> %s\n",
[[[NSString stringWithUTF8String:FILE] lastPathComponent] UTF8String],
LINE, func);
(NSLog)((format), ##VA_ARGS);
fprintf(stderr, "-------\n");
} while (0)
21.給navigation Bar 設(shè)置 title 顏色
UIColor *whiteColor = [UIColor whiteColor];NSDictionary *dic = [NSDictionary dictionaryWithObject:whiteColor forKey:NSForegroundColorAttributeName];
[self.navigationController.navigationBar setTitleTextAttributes:dic];
22.如何把一個CGPoint存入數(shù)組里
CGPoint itemSprite1position = CGPointMake(100, 200);NSMutableArray * array = [[NSMutableArray alloc] initWithObjects:NSStringFromCGPoint(itemSprite1position),nil];
// 從數(shù)組中取值的過程是這樣的
CGPoint point = CGPointFromString([array objectAtIndex:0]);NSLog(@"point is %@.", NSStringFromCGPoint(point));
//可以用NSValue進行基礎(chǔ)數(shù)據(jù)的保存,用這個方法更加清晰明確。
CGPoint itemSprite1position = CGPointMake(100, 200);
NSValue *originValue = [NSValue valueWithCGPoint:itemSprite1position];
NSMutableArray * array = [[NSMutableArray alloc] initWithObjects:originValue, nil];
// 從數(shù)組中取值的過程是這樣的:
NSValue *currentValue = [array objectAtIndex:0];
CGPoint point = [currentValue CGPointValue];
NSLog(@"point is %@.", NSStringFromCGPoint(point));
現(xiàn)在Xcode7后OC支持泛型了,可以用NSMutableArray<NSString *> *array來保存。
23.UIColor 獲取 RGB 值
UIColor *color = [UIColor colorWithRed:0.0 green:0.0 blue:1.0 alpha:1.0];
const CGFloat *components = CGColorGetComponents(color.CGColor);
NSLog(@"Red: %f", components[0]);
NSLog(@"Green: %f", components[1]);
NSLog(@"Blue: %f", components[2]);
NSLog(@"Alpha: %f", components[3]);
24.修改textField的placeholder的字體顏色、大小
self.textField.placeholder = @"username is in here!";
[self.textField setValue:[UIColor redColor] forKeyPath:@"_placeholderLabel.textColor"];
[self.textField setValue:[UIFont boldSystemFontOfSize:16] forKeyPath:@"_placeholderLabel.font"];
25.兩點之間的距離
static inline CGFloat CGPointDistanceBetweenTwoPoints(CGPoint point1, CGPoint point2)
{
CGFloat dx = point2.x - point1.x; CGFloat dy = point2.y - point1.y; return sqrt(dxdx + dydy);
}
26.iOS開發(fā)-關(guān)閉/收起鍵盤方法總結(jié)
//1、點擊Return按扭時收起鍵盤
- (BOOL)textFieldShouldReturn:(UITextField *)textField { return [textField resignFirstResponder]; }
//2、點擊背景View收起鍵盤(你的View必須是繼承于UIControl)
[self.view endEditing:YES];
//3、你可以在任何地方加上這句話,可以用來統(tǒng)一收起鍵盤
[[[UIApplication sharedApplication] keyWindow] endEditing:YES];
27.在使用 ImagesQA.xcassets 時需要注意
將圖片直接拖入image到ImagesQA.xcassets中時,圖片的名字會保留。這個時候如果圖片的名字過長,那么這個名字會存入到ImagesQA.xcassets中,名字過長會引起SourceTree判斷異常。
28.UIPickerView 判斷開始選擇到選擇結(jié)束
開始選擇的,需要在繼承UiPickerView,創(chuàng)建一個子類,在子類中重載
- (UIView)hitTest:(CGPoint)point withEvent:(UIEvent)event
當[super hitTest:point withEvent:event]
返回不是nil的時候,說明是點擊中UIPickerView中了。結(jié)束選擇的, 實現(xiàn)UIPickerView的delegate方法
- (void)pickerView:(UIPickerView*)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
當調(diào)用這個方法的時候,說明選擇已經(jīng)結(jié)束了。
29.iOS模擬器 鍵盤事件
當iOS模擬器 選擇了Keybaord->Connect Hardware keyboard 后,不彈出鍵盤。
//當代碼中添加了
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide) name:UIKeyboardWillHideNotification object:nil];
進行鍵盤事件的獲取。那么在此情景下將不會調(diào)用- (void)keyboardWillHide
.因為沒有鍵盤的隱藏和顯示。
30.在ios7上使用size classes后上面下面黑色
使用了size classes后,在ios7的模擬器上出現(xiàn)了上面和下面部分的黑色
可以在General->App Icons and Launch Images->Launch Images Source中設(shè)置Images.xcassets來解決。

31.線程中更新 UILabel的text
[self.label1 performSelectorOnMainThread:@selector(setText:) withObject:textDisplay waitUntilDone:YES];
label1 為UILabel,當在子線程中,需要進行text的更新的時候,可以使用這個方法來更新。其他的UIView 也都是一樣的。
32.使用UIScrollViewKeyboardDismissMode實現(xiàn)了Message app的行為
像Messages app一樣在滾動的時候可以讓鍵盤消失是一種非常好的體驗。然而,將這種行為整合到你的app很難。幸運的是,蘋果給UIScrollView添加了一個很好用的屬性keyboardDismissMode,這樣可以方便很多。
現(xiàn)在僅僅只需要在Storyboard中改變一個簡單的屬性,或者增加一行代碼,你的app可以和辦到和Messages app一樣的事情了。
這個屬性使用了新的UIScrollViewKeyboardDismissMode enum枚舉類型。這個enum枚舉類型可能的值如下:
typedef NS_ENUM(NSInteger, UIScrollViewKeyboardDismissMode)
{
UIScrollViewKeyboardDismissModeNone,
UIScrollViewKeyboardDismissModeOnDrag, // dismisses the keyboard when a drag begins
UIScrollViewKeyboardDismissModeInteractive, // the keyboard follows the dragging touch off screen, and may be pulled upward again to cancel the dismiss
} NS_ENUM_AVAILABLE_IOS(7_0);
以下是讓鍵盤可以在滾動的時候消失需要設(shè)置的屬性:

33.報錯 "_sqlite3_bind_blob", referenced from:
將 sqlite3.dylib加載到framework
34.ios7 statusbar 文字顏色
iOS7上,默認status bar字體顏色是黑色的,要修改為白色的需要在infoPlist里設(shè)置UIViewControllerBasedStatusBarAppearance為NO,然后在代碼里添加:
[application setStatusBarStyle:UIStatusBarStyleLightContent];
35.獲得當前硬盤空間
NSFileManager *fm = [NSFileManager defaultManager];
NSDictionary *fattributes = [fm attributesOfFileSystemForPath:NSHomeDirectory() error:nil];
NSLog(@"容量%lldG",[[fattributes objectForKey:NSFileSystemSize] longLongValue]/1000000000);
NSLog(@"可用%lldG",[[fattributes objectForKey:NSFileSystemFreeSize] longLongValue]/1000000000);
36.給UIView 設(shè)置透明度,不影響其他sub views
UIView設(shè)置了alpha值,但其中的內(nèi)容也跟著變透明。有沒有解決辦法?
設(shè)置background color的顏色中的透明度
比如:
[self.testView setBackgroundColor:[UIColor colorWithRed:0.0 green:1.0 blue:1.0 alpha:0.5]];
設(shè)置了color的alpha, 就可以實現(xiàn)背景色有透明度,當其他sub views不受影響給color 添加 alpha,或修改alpha的值。
// Returns a color in the same color space as the receiver with the specified alpha component.
- (UIColor *)colorWithAlphaComponent:(CGFloat)alpha;
// eg.
[view.backgroundColor colorWithAlphaComponent:0.5];
37.將color轉(zhuǎn)為UIImage
//將color轉(zhuǎn)為UIImage
- (UIImage *)createImageWithColor:(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;
}
38.NSTimer 用法
NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:.02 target:self selector:@selector(tick:) userInfo:nil repeats:YES];
[[NSRunLoop currentRunLoop] addTimer:timer forMode:NSRunLoopCommonModes];
在NSRunLoop 中添加定時器.
38.Bundle identifier 應(yīng)用標示符
Bundle identifier 是應(yīng)用的標示符,表明應(yīng)用和其他APP的區(qū)別。
39.NSDate 獲取幾年前的時間
// 獲取到40年前的日期
NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *dateComponents = [[NSDateComponents alloc] init];
[dateComponents setYear:-40];
self.birthDate = [gregorian dateByAddingComponents:dateComponents toDate:[NSDate date] options:0];
40.iOS加載啟動圖的時候隱藏statusbar
只需需要在info.plist中加入Status bar is initially hidden 設(shè)置為YES就好!```

41.iOS 開發(fā),工程中混合使用 ARC 和非ARC
Xcode 項目中我們可以使用 ARC 和非 ARC 的混合模式。
如果你的項目使用的非 ARC 模式,則為 ARC 模式的代碼文件加入 -fobjc-arc 標簽。
如果你的項目使用的是 ARC 模式,則為非 ARC 模式的代碼文件加入 -fno-objc-arc 標簽。
添加標簽的方法:
打開:你的target -> Build Phases -> Compile Sources.
雙擊對應(yīng)的 *.m 文件
在彈出窗口中輸入上面提到的標簽 -fobjc-arc / -fno-objc-arc
點擊 done 保存
42.iOS7 中 boundingRectWithSize:options:attributes:context:計算文本尺寸的使用
之前使用了NSString類的sizeWithFont:constrainedToSize:lineBreakMode:方法,但是該方法已經(jīng)被iOS7 Deprecated了,而iOS7新出了一個boudingRectWithSize:options:attributes:context方法來代替。而具體怎么使用呢,尤其那個attribute.
NSDictionary *attribute = @{NSFontAttributeName: [UIFont systemFontOfSize:13]};
CGSize size = [@"相關(guān)NSString" boundingRectWithSize:CGSizeMake(100, 0) options: NSStringDrawingTruncatesLastVisibleLine | NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading attributes:attribute context:nil].size;
43.NSDate使用 注意
NSDate 在保存數(shù)據(jù),傳輸數(shù)據(jù)中,一般最好使用UTC時間。
在顯示到界面給用戶看的時候,需要轉(zhuǎn)換為本地時間。
44.在UIViewController中property的一個UIViewController的Present問題
如果在一個UIViewController A中有一個property屬性為UIViewController B,實例化后,將BVC.view 添加到主UIViewController A.view上,如果在viewB上進行
- (void)presentViewController:(UIViewController *)viewControllerToPresent animated: (BOOL)flag completion:(void (^)(void))completion NS_AVAILABLE_IOS(5_0);
的操作將會出現(xiàn),“ **Presenting view controllers on detached view controllers is discouraged **” 的問題。
以為BVC已經(jīng)present到AVC中了,所以再一次進行會出現(xiàn)錯誤。
可以使用
[self.view.window.rootViewController presentViewController:imagePicker animated:YES completion:^{ NSLog(@"Finished"); }];
來解決。
45.UITableViewCell indentationLevel 使用
UITableViewCell 屬性 NSInteger indentationLevel 的使用, 對cell設(shè)置 indentationLevel的值,可以將cell 分級別。
還有 CGFloat indentationWidth; 屬性,設(shè)置縮進的寬度。
總縮進的寬度: **indentationLevel * indentationWidth**
46.ActivityViewController 使用AirDrop分享
使用AirDrop 進行分享:
NSArray *array = @[@"test1", @"test2"];UIActivityViewController *activityVC = [[UIActivityViewController alloc] initWithActivityItems:array applicationActivities:nil];[self presentViewController:activityVC animated:YES completion:^{ NSLog(@"Air"); }];
就可以彈出界面:

47.獲取CGRect的height
獲取CGRect的height, 除了self.createNewMessageTableView.frame.size.height
這樣進行點語法獲取。
還可以使用CGRectGetHeight(self.createNewMessageTableView.frame)
進行直接獲取。
除了這個方法還有func CGRectGetWidth(rect: CGRect) -> CGFloat
等等簡單地方法
func CGRectGetMinX(rect: CGRect) -> CGFloat
func CGRectGetMidX(rect: CGRect) -> CGFloat
func CGRectGetMaxX(rect: CGRect) -> CGFloat
func CGRectGetMinY(rect: CGRect) -> CGFloat
48.打印 %
NSString *printPercentStr = [NSString stringWithFormat:@"%%"];
49.在工程中查看是否使用 IDFA
allentekiMac-mini:JiKaTongGit lihuaxie$ grep -r advertisingIdentifier .
grep: ./ios/Framework/AMapSearchKit.framework/Resources: No such file or directory
Binary file ./ios/Framework/MAMapKit.framework/MAMapKit matches
Binary file ./ios/Framework/MAMapKit.framework/Versions/2.4.1.e00ba6a/MAMapKit matches
Binary file ./ios/Framework/MAMapKit.framework/Versions/Current/MAMapKit matches
Binary file ./ios/JiKaTong.xcodeproj/project.xcworkspace/xcuserdata/lihuaxie.xcuserdatad/UserInterfaceState.xcuserstate matches
allentekiMac-mini:JiKaTongGit lihuaxie$
打開終端,到工程目錄中, 輸入:
grep -r advertisingIdentifier .
可以看到那些文件中用到了IDFA,如果用到了就會被顯示出來。
50.APP 屏蔽 觸發(fā)事件
// Disable user interaction when download finishes[[UIApplication sharedApplication] beginIgnoringInteractionEvents];
51.設(shè)置Status bar顏色
status bar的顏色設(shè)置:
如果沒有navigation bar, 直接設(shè)置
// make status bar background color
self.view.backgroundColor = COLOR_APP_MAIN;
如果有navigation bar, 在navigation bar 添加一個view來設(shè)置顏色。
// status bar color
UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, -20, ScreenWidth, 20)];
[view setBackgroundColor:COLOR_APP_MAIN];
[viewController.navigationController.navigationBar addSubview:view];```
52.NSDictionary 轉(zhuǎn) NSString
// Start
NSDictionary *parametersDic = [NSDictionary dictionaryWithObjectsAndKeys:self.providerStr, KEY_LOGIN_PROVIDER,token, KEY_TOKEN,response, KEY_RESPONSE,nil];
NSData *jsonData = parametersDic == nil ? nil : [NSJSONSerialization dataWithJSONObject:parametersDic options:0 error:nil];
NSString *requestBody = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
將dictionary 轉(zhuǎn)化為 NSData, data 轉(zhuǎn)化為 string .
53.iOS7 中UIButton setImage 沒有起作用
如果在iOS7 中進行設(shè)置image 沒有生效。
那么說明UIButton的 enable 屬性沒有生效是NO的。 需要設(shè)置enable 為YES。
54.User-Agent 判斷設(shè)備UIWebView 會根據(jù)User-Agent 的值來判斷需要顯示哪個界面。如果需要設(shè)置為全局,那么直接在應(yīng)用啟動的時候加載。
-(void)appendUserAgent
{
NSString *oldAgent = [self.WebView stringByEvaluatingJavaScriptFromString:@"navigator.userAgent"];
NSString *newAgent = [oldAgent stringByAppendingString:@"iOS"];
NSDictionary *dic = [[NSDictionary alloc] initWithObjectsAndKeys:
newAgent, @"UserAgent", nil];
[[NSUserDefaults standardUserDefaults] registerDefaults:dic];
}
@“iOS" 為添加的自定義。
55.UIPasteboard 屏蔽paste 選項
當UIpasteboard的string 設(shè)置為@“” 時,那么string會成為nil。 就不會出現(xiàn)paste的選項。 ```
56.class_addMethod 使用
**當 ARC 環(huán)境下**
class_addMethod([self class], @selector(resolveThisMethodDynamically), (IMP) myMethodIMP, "v@:");
使用的時候@selector 需要使用super的class,不然會報錯。
**當MRC環(huán)境下**
class_addMethod([EmptyClass class], @selector(sayHello2), (IMP)sayHello, "v@:");
可以任意定義。但是系統(tǒng)會出現(xiàn)警告,忽略警告就可以。```
57.AFNetworking 傳送 form-data
將JSON的數(shù)據(jù),轉(zhuǎn)化為NSData, 放入Request的body中。 發(fā)送到服務(wù)器就是form-data格式。```
58.非空判斷注意
BOOL hasBccCode = YES;
if ( nil == bccCodeStr || [bccCodeStr isKindOfClass:[NSNull class]] || [bccCodeStr isEqualToString:@""])
{
hasBccCode = NO;
}
如果進行非空判斷和類型判斷時,**需要新進行類型判斷,再進行非空判斷,不然會crash**。```
59.iOS 8.4 UIAlertView 鍵盤顯示問題
可以在調(diào)用UIAlertView 之前進行鍵盤是否已經(jīng)隱藏的判斷。
@property (nonatomic, assign) BOOL hasShowdKeyboard;
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(showKeyboard) name:UIKeyboardWillShowNotification object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(dismissKeyboard) name:UIKeyboardDidHideNotification object:nil];
(void)showKeyboard
{
self.hasShowdKeyboard = YES;
}(void)dismissKeyboard
{
self.hasShowdKeyboard = NO;
}
while ( self.hasShowdKeyboard )
{
[[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantFuture]];
}
UIAlertView* alerview = [[UIAlertView alloc] initWithTitle:@"" message:@"取消修改?" delegate:self cancelButtonTitle:@"取消" otherButtonTitles: @"確定", nil];
[alerview show];
60.模擬器中文輸入法設(shè)置
模擬器默認的配置種沒有“小地球”,只能輸入英文。加入中文方法如下:
選擇Settings--->General-->Keyboard-->International KeyBoards-->Add New Keyboard-->Chinese Simplified(PinYin) 即我們一般用的簡體中文拼音輸入法,配置好后,再輸入文字時,點擊彈出鍵盤上的“小地球”就可以輸入中文了。如果不行,可以長按“小地球”選擇中文。
61.iPhone number pad
phone 的鍵盤類型:
1.number pad 只能輸入數(shù)字,不能切換到其他輸入:

2.phone pad 類型: 撥打電話的時候使用,可以輸入數(shù)字和 + * # ```

62.UIView 自帶動畫翻轉(zhuǎn)界面
- (IBAction)changeImages:(id)sender
{
CGContextRef context = UIGraphicsGetCurrentContext();
[UIView beginAnimations:nil context:context];
[UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];
[UIView setAnimationDuration:1.0];
[UIView setAnimationTransition:UIViewAnimationTransitionCurlDown forView:_parentView cache:YES];
[UIView setAnimationTransition:UIViewAnimationTransitionCurlUp forView:_parentView cache:YES];
[UIView setAnimationTransition:UIViewAnimationTransitionFlipFromLeft forView:_parentView cache:YES];
[UIView setAnimationTransition:UIViewAnimationTransitionFlipFromRight forView:_parentView cache:YES];
NSInteger purple = [[_parentView subviews] indexOfObject:self.image1];
NSInteger maroon = [[_parentView subviews] indexOfObject:self.image2];
[_parentView exchangeSubviewAtIndex:purple withSubviewAtIndex:maroon];
[UIView setAnimationDelegate:self];
[UIView commitAnimations];
}
63.KVO 監(jiān)聽其他類的變量
[[HXSLocationManager sharedManager] addObserver:self forKeyPath:@"currentBoxEntry.boxCodeStr" options:NSKeyValueObservingOptionNew | NSKeyValueObservingOptionInitial | NSKeyValueObservingOptionOld context:nil];
在實現(xiàn)的類self中,進行[HXSLocationManager sharedManager]類中的變量@“currentBoxEntry.boxCodeStr” 監(jiān)聽。
64.ios9 crash animateWithDuration
在iOS9 中,如果進行animateWithDuration 時,view被release 那么會引起crash。
[UIView animateWithDuration:0.25f animations:^{
self.frame = selfFrame;
} completion:^(BOOL finished) {
if (finished)
{
[super removeFromSuperview];
}
}];
會crash。
[UIView animateWithDuration:0.25f delay:0 usingSpringWithDamping:1.0 initialSpringVelocity:1.0 options:UIViewAnimationOptionCurveLinear animations:^{
self.frame = selfFrame;
} completion:^(BOOL finished) {
[super removeFromSuperview];
}];
不會Crash。
65.對NSString進行URL編碼轉(zhuǎn)換
iPTV項目中在刪除影片時,URL中需傳送用戶名與影片ID兩個參數(shù)。當用戶名中帶中文字符時,刪除失敗。
之前測試時,手機號綁定的用戶名是英文或數(shù)字。換了手機號測試時才發(fā)現(xiàn)這個問題。
對于URL中有中文字符的情況,需對URL進行編碼轉(zhuǎn)換。
urlStr = [urlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
66.Xcode iOS加載圖片只能用PNG
雖然在Xcode可以看到j(luò)pg的圖片,但是在加載的時候會失敗。錯誤為 Could not load the "ReversalImage1" image referenced from a nib in the bun
**必須使用PNG的圖片。**
**如果需要使用JPG 需要添加后綴**
[UIImage imageNamed:@"myImage.jpg"];
67.保存全屏為image
CGSize imageSize = [[UIScreen mainScreen] bounds].size;
UIGraphicsBeginImageContextWithOptions(imageSize, NO, 0);
CGContextRef context = UIGraphicsGetCurrentContext();
for (UIWindow * window in [[UIApplication sharedApplication] windows])
{
if (![window respondsToSelector:@selector(screen)] || [window screen] == [UIScreen mainScreen])
{
CGContextSaveGState(context);
CGContextTranslateCTM(context, [window center].x, [window center].y);
CGContextConcatCTM(context, [window transform]);
CGContextTranslateCTM(context, -[window bounds].size.width*[[window layer] anchorPoint].x, -[window bounds].size.height*[[window layer] anchorPoint].y);
[[window layer] renderInContext:context];
CGContextRestoreGState(context);
}
}
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
68.判斷定位狀態(tài) locationServicesEnabled
這個[CLLocationManager locationServicesEnabled]檢測的是整個iOS系統(tǒng)的位置服務(wù)開關(guān),無法檢測當前應(yīng)用是否被關(guān)閉。
通過:
CLAuthorizationStatus status = [CLLocationManager authorizationStatus];
if (kCLAuthorizationStatusDenied == status || kCLAuthorizationStatusRestricted == status)
{
[self locationManager:self.locationManager didUpdateLocations:nil];
}
else
{
// the user has closed this function
[self.locationManager startUpdatingLocation];
}
**CLAuthorizationStatus**來判斷是否可以訪問GPS
69.微信分享的時候注意大小
text 的大小必須 大于0 小于 10k
image 必須 小于 64k
url 必須 大于 0k```
70.圖片緩存的清空
一般使用SDWebImage 進行圖片的顯示和緩存,一般緩存的內(nèi)容比較多了就需要進行清空緩存
清除SDWebImage的內(nèi)存和硬盤時,可以同時清除session 和 cookie的緩存。
// 清理內(nèi)存
[[SDImageCache sharedImageCache] clearMemory];
// 清理webview 緩存
NSHTTPCookieStorage *storage = [NSHTTPCookieStorage sharedHTTPCookieStorage];
for (NSHTTPCookie *cookie in [storage cookies])
{
[storage deleteCookie:cookie];
}
NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration];
[config.URLCache removeAllCachedResponses];
[[NSURLCache sharedURLCache] removeAllCachedResponses];
// 清理硬盤
[[SDImageCache sharedImageCache] clearDiskOnCompletion:^{
[MBProgressHUD hideAllHUDsForView:self.view animated:YES];
[self.tableView reloadData];
}];
71.TableView Header View 跟隨Tableview 滾動
當tableview的類型為 plain的時候,header View 就會停留在最上面。
當類型為 group的時候,header view 就會跟隨tableview 一起滾動了。
72.TabBar的title 設(shè)置
在xib 或 storyboard 中可以進行tabBar的設(shè)置:

其中badge 是自帶的在圖標上添加一個角標。
- self.navigationItem.title 設(shè)置navigation的title 需要用這個進行設(shè)置。
- self.title 在tab bar的主VC 中,進行設(shè)置self.title 會導致navigation 的title 和 tab bar的title一起被修改。
73.UITabBar,移除頂部的陰影
添加這兩行代碼:
[[UITabBar appearance] setShadowImage:[[UIImage alloc] init]];
[[UITabBar appearance] setBackgroundImage:[[UIImage alloc] init]];
頂部的陰影是在UIWindow上的,所以不能簡單的設(shè)置就去除。```
74.當一行中,多個UIKit 都是動態(tài)的寬度設(shè)置:```

設(shè)置horizontal的值,表示出現(xiàn)內(nèi)容很長的時候,優(yōu)先壓縮這個UIKit。```
75.JSON的“<null>” 轉(zhuǎn)換為nil
//使用AFNetworking 時, 使用
AFJSONResponseSerializer *response = [[AFJSONResponseSerializer alloc] init];
response.removesKeysWithNullValues = YES;
_sharedClient.responseSerializer = response;
這個參數(shù) removesKeysWithNullValues 可以將null的值刪除,那么就Value為nil了
76.iOS 隨機顏色
view.backgroundColor = [UIColor colorWithRed:arc4random_uniform(255)/255.0 green:arc4random_uniform(255)/255.0 blue:arc4random_uniform(255)/255.0 alpha:1];```
77.獲取時間戳
-(NSString *)created_at{
// Mon May 09 15:21:58 +0800 2016
//獲取微博發(fā)送時間
//把獲得的字符串時間 轉(zhuǎn)成 時間戳
//EEE(星期) MMM(月份)dd(天) HH小時 mm分鐘 ss秒 Z時區(qū) yyyy年
NSDateFormatter *format = [[NSDateFormatter alloc]init];
format.dateFormat = @"EEE MMM dd HH:mm:ss Z yyyy";
//設(shè)置地區(qū)
format.locale = [[NSLocale alloc]initWithLocaleIdentifier:@"en_US"];
//微博發(fā)送時間
NSDate *weiboDate = [format dateFromString:<"要展示的字符串">];
//獲取當前時間
NSDate *nowDate = [NSDate new];
long nowTime = [nowDate timeIntervalSince1970];
long weiboTime = [weiboDate timeIntervalSince1970];
//微博時間和當前時間的時間差
long time = nowTime-weiboTime;
if (time<60) {//一分鐘內(nèi) 顯示剛剛
return @"剛剛";
}else if (time>60&&time<=3600){
return [NSString stringWithFormat:@"%d分鐘前",(int)time/60];
}else if (time>3600&&time<3600*24){
return [NSString stringWithFormat:@"%d小時前",(int)time/3600];
}else{//直接顯示日期
format.dateFormat = @"MM月dd日";
return [format stringFromDate:weiboDate];
}
}
```swift
78.NSString的一些特殊情況
//__autoreleasing 對象設(shè)置為這樣,要等到離自己最近的釋放池銷毀時才release
//__unsafe__unretained不安全不釋放,為了兼容過去而存在,跟__weak很像,但是這個對象被銷毀后還在,不像__weak那樣設(shè)置為nil
//__weak 一創(chuàng)建完,要是沒有引用,馬上釋放,將對象置nil
//
__weak NSMutableString *str = [NSMutableString stringWithFormat:@"%@",@"xiaobai"];
//__weak 的話但是是alloc的對象,要交給autorelease管理
//arc下,不要release 和 autorelease因為
79.設(shè)置UITabBarItem背景圖片
if(iOS7)
{
item = [iteminitWithTitle:title[i]image:[unSelectImageimageWithRenderingMode:UIImageRenderingModeAlwaysOriginal]selectedImage:[selectImageimageWithRenderingMode:UIImageRenderingModeAlwaysOriginal]];
}
else
{
itemsetFinishedSelectedImage:selectImagewithFinishedUnselectedImage:unSelectImage];
item.title= title[i];
}
80.app跳轉(zhuǎn)到safari
NSURL* url = [NSURL URLWithString:urlStr];
[[UIApplication sharedApplication] openURL:url];
81.每個cell的高度,(使用autolayout可以實現(xiàn)自動算高)
- (CGFloat)tableView:(UITableView *)tableView estimatedHeightForRowAtIndexPath:(NSIndexPath *)indexPath
{
//讓tableview自動根據(jù)cell中的子視圖的約束,來計算自己的高度
return UITableViewAutomaticDimension;
}
82.解決編碼問題
中文應(yīng)用都要遇到一個很頭疼的問題:文字編碼,漢字的 GBK 和 國際通用的 UTF-8 的互相轉(zhuǎn)化稍一不慎,就會滿屏亂碼。下面介紹 UTF-8 和 GBK 的 NSString 相互轉(zhuǎn)化的方法!
從 GBK 轉(zhuǎn)到 UTF-8:
用 NSStringEncoding enc = CFStringConvertEncodingToNSStringEncoding(kCFStringEncodingGB_18030_2000) ,然后就可以用initWithData:encoding來實現(xiàn)。
從 UTF-8 轉(zhuǎn)到 GBK:
CFStringConvertEncodingToNSStringEncoding(kCFStringEncodingGB_18030_2000),得到的enc卻是kCFStringEncodingInvalidId。
沒關(guān)系,試試 NSData *data=[nsstring dataUsingEncoding:-2147482063];
注意:必須使用kCFStringEncodingGB_18030_2000這個字符集,那個kCFStringEncodingGB_2312_80試了也不行。
下圖為證~!??



83.電池條的顏色
//方式一:
//新的電池條 風格調(diào)整: 在需要變化電池條樣式的vc中, 重寫下方方法即可
//新的方式: 當前電池條的顏色 基于當前控制器的設(shè)置.
- (UIStatusBarStyle)preferredStatusBarStyle{
return UIStatusBarStyleLightContent;//白
}
//方式二:
//舊的方式: 電池條的顏色與VC無關(guān). 這要修改plist文件, 把View controller-based status bar appearance屬性設(shè)置為NO
- (void)viewDidLoad {
[super viewDidLoad];
//設(shè)置整個應(yīng)用程序中所有頁面的電池條顏色
[UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleLightContent;
}
//還需要再info.plist中設(shè)置

84.xcode統(tǒng)計代碼量方法:
1.打開終端,用cd命令 定位到工程所在的目錄,然后調(diào)用以下命名即可把每個源代碼文件行數(shù)及總數(shù)統(tǒng)計出來:
find . "(" -name "*.m" -or -name "*.mm" -or -name "*.cpp" -or -name "*.h" -or -name "*.rss" ")" -print | xargs wc -l
85:iOS適配 之 關(guān)于info.plist 第三方登錄 添加URL Schemes白名單
近期蘋果公司iOS 9系統(tǒng)策略更新,限制了http協(xié)議的訪問,此外應(yīng)用需要在“Info.plist”中將要使用的URL Schemes列為白名單,才可正常檢查其他應(yīng)用是否安裝。
受此影響,當你的應(yīng)用在iOS 9中需要使用 QQ/QQ空間/支付寶/微信SDK 的相關(guān)能力(分享、收藏、支付、登錄等)時,需要在“Info.plist”里增加如下代碼:
<key>LSApplicationQueriesSchemes</key>
<array>
<!-- 微信 URL Scheme 白名單-->
<string>wechat</string>
<string>weixin</string>
<!-- 新浪微博 URL Scheme 白名單-->
<string>sinaweibohd</string>
<string>sinaweibo</string>
<string>sinaweibosso</string>
<string>weibosdk</string>
<string>weibosdk2.5</string>
<!-- QQ、Qzone URL Scheme 白名單-->
<string>mqqapi</string>
<string>mqq</string>
<string>mqqOpensdkSSoLogin</string>
<string>mqqconnect</string>
<string>mqqopensdkdataline</string>
<string>mqqopensdkgrouptribeshare</string>
<string>mqqopensdkfriend</string>
<string>mqqopensdkapi</string>
<string>mqqopensdkapiV2</string>
<string>mqqopensdkapiV3</string>
<string>mqzoneopensdk</string>
<string>wtloginmqq</string>
<string>wtloginmqq2</string>
<string>mqqwpa</string>
<string>mqzone</string>
<string>mqzonev2</string>
<string>mqzoneshare</string>
<string>wtloginqzone</string>
<string>mqzonewx</string>
<string>mqzoneopensdkapiV2</string>
<string>mqzoneopensdkapi19</string>
<string>mqzoneopensdkapi</string>
<string>mqzoneopensdk</string>
<!-- 支付寶 URL Scheme 白名單-->
<string>alipay</string>
<string>alipayshare</string>
</array>
具體操作步驟:
右鍵 info.plist /Open as/Source Code 將上面的代碼粘貼上去即可!
86.最近經(jīng)常看到有人在群里問關(guān)于導航條透明的,廢話不多說,直接上代碼:
在ViewDidLoad方法里加上這三行代碼:
self.navigationController.navigationBar.translucent = YES;
[self.navigationController.navigationBar setBackgroundImage:[[UIImage alloc] init] forBarMetrics:UIBarMetricsDefault];
[self.navigationController.navigationBar setShadowImage:[[UIImage alloc] init]];
在viewWillDisappear方法里加上這三行代碼:
self.navigationController.navigationBar.translucent = NO;
[self.navigationController.navigationBar setBackgroundImage:nil forBarMetrics:UIBarMetricsDefault];
[self.navigationController.navigationBar setShadowImage:nil];
self.navigationController.navigationBar.translucent分別表示開啟、關(guān)閉導航條透明度
self.navigationController.navigationBar setBackgroundImage分別表示給導航條背景設(shè)置成空圖片和恢復默認
[self.navigationController.navigationBar setShadowImage給賦值空的UIImage對象的目的是為了去除導航條透明時下面的黑線,當然賦值nil也是恢復默認咯
在這里有一點需要說明,如果沒有禁用導航控制器的右滑pop手勢的話,在viewWillDisappear里寫那代碼可能會有問題哦
導航側(cè)滑pop手勢沒有禁用的時候,右滑、在上一個界面快完全顯示的時候,左滑回去,然后。。。自己去試試吧,哈哈
87.所有屏幕尺寸的宏定義:
#define IPHONE5 ([UIScreen instancesRespondToSelector:@selector(currentMode)] ? CGSizeEqualToSize(CGSizeMake(640, 1136), [[UIScreen mainScreen] currentMode].size) : 0)
#define IPHONE4 ([UIScreen instancesRespondToSelector:@selector(currentMode)] ? CGSizeEqualToSize(CGSizeMake(640, 960), [[UIScreen mainScreen] currentMode].size) : 0)
#define IPHONE6 ([UIScreen instancesRespondToSelector:@selector(currentMode)] ? CGSizeEqualToSize(CGSizeMake(750, 1334), [[UIScreen mainScreen] currentMode].size) : 0)
#define IPHONE6PLUS ([UIScreen instancesRespondToSelector:@selector(currentMode)] ? CGSizeEqualToSize(CGSizeMake(1242, 2208), [[UIScreen mainScreen] currentMode].size) : 0)