您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 程式開發 >> iOS 開發綜合

iOS 開發筆記 26:iPhone 開發常用技巧大彙整

編輯:iOS 開發綜合

做 iOS 開發久了,總會累積一批「隨時要翻、每次都要重新查」的小片段。這一篇把最常被用到的招式整理成一份速查表,從 Runtime 判斷、通知機制,到圖片處理、手勢與版面配置,方便日後直接抄用。

一、Runtime 檢查與延遲執行

呼叫一個不確定是否存在的 Selectors 之前,先問一句比較安全,可以避免 unrecognized selector 崩潰:

if ([object respondsToSelector:@selector(someMethod)]) {
    [object someMethod];
}

需要延遲一點點再執行(例如畫面切換後才做某些事),用 performSelector:withObject:afterDelay: 最省事:

[self performSelector:@selector(reloadData) withObject:nil afterDelay:0.3];

二、模擬器的 App 目錄怎麼找

想直接看 App 寫進 Documents 的檔案,可以到模擬器的應用目錄翻:

/[user]/Library/Application Support/iPhone Simulator/4.2/Applications/B0E3EC07-F395-408F-9B94-A5B0BAECBC2E/Documents/personal.plist

實務上 Bundle Identifier 那段 GUID 每次安裝都會變,通常直接用終端機 find 或 Xcode 的 Devices 面板下載容器,會比記路徑可靠。

三、自訂通知(NSNotification)

發送端帶一份 userInfo 出去:

NSDictionary *info = [[NSDictionary alloc] initWithObjectsAndKeys:@"ret", nil];
[[NSNotificationCenter defaultCenter] postNotificationName:@"LoginSuccessful"
                                                    object:self
                                                  userInfo:info];

接收端記得在啟動時註冊,並在 dealloc 移除,否則容易收到已釋放物件的通知:

[[NSNotificationCenter defaultCenter] addObserver:self
                                        selector:@selector(loginSuccessful:)
                                            name:@"LoginSuccessful"
                                          object:nil];

四、用 Regular Expression 驗證 Email

NSPredicate 搭配正規表達式,是舊專案裡最常見的寫法:

-(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];
}

五、圖片縮放與上傳

把大圖先降成你要的尺寸,能省下不少記憶體與流量:

- (UIImage *)imageWithImage:(UIImage *)image scaledToSize:(CGSize)newSize {
    UIGraphicsBeginImageContext(newSize);
    [image drawInRect:CGRectMake(0, 0, newSize.width, newSize.height)];
    UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return newImage;
}

上傳則是組 multipart/form-data 的 POST 請求,先壓縮再送出:

NSString *urlString = @"https://192.168.1.113:8090/text/UploadServlet";
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:urlString]];
[request setHTTPMethod:@"POST"];

NSString *boundary = @"---------------------------14737809831466499882746641449";
[request addValue:[NSString stringWithFormat:@"multipart/form-data; boundary=%@", boundary]
  forHTTPHeaderField:@"Content-Type"];

UIImage *image = [UIImage imageNamed:@"1.jpg"];
NSData *imageData = UIImageJPEGRepresentation(image, 0.5);

NSMutableData *body = [NSMutableData data];
[body appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:@"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:imageData];
[body appendData:[[NSString stringWithFormat:@"\r\n--%@--\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[request setHTTPBody:body];

NSURLResponse *response = nil;
NSError *error = nil;
NSData *returnData = [NSURLConnection sendSynchronousRequest:request
                                          returningResponse:&response
                                                      error:&error];

提醒一句:同步請求會卡住主線程,正式環境請改用非同步(NSURLSession 或 ASIHTTPRequest)。

六、相簿與相機的選圖流程

UIImagePickerControllerSourceType sourceType = UIImagePickerControllerSourceTypeCamera;
if (![UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
    sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
}
UIImagePickerController *picker = [[UIImagePickerController alloc] init];
picker.delegate = self;
picker.allowsEditing = YES;
picker.sourceType = sourceType;
[self presentModalViewController:picker animated:YES];

選完之後,從 info 拿編輯過的圖,再回到自己的畫面:

-(void)imagePickerController:(UIImagePickerController *)picker
didFinishPickingMediaWithInfo:(NSDictionary *)info {
    [picker dismissModalViewControllerAnimated:YES];
    UIImage *image = [info objectForKey:UIImagePickerControllerEditedImage];
    [self performSelector:@selector(selectPic:) withObject:image afterDelay:0.1];
}

-(void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {
    [picker dismissModalViewControllerAnimated:YES];
}

七、頁面跳轉與左右兩側的導航按鈕

WEBViewController *nextWebView = [[WEBViewController alloc] initWithNibName:@"WEBViewController" bundle:nil];
[self presentModalViewController:nextWebView animated:YES];

UIBarButtonItem *rightButton = [[UIBarButtonItem alloc] initWithTitle:@"右邊"
                                                               style:UIBarButtonItemStyleDone
                                                              target:self
                                                              action:@selector(clickRightButton)];
[self.navigationItem setRightBarButtonItem:rightButton];

// 需要自訂版面時,把系統導航列藏起來
self.navigationController.navigationBarHidden = YES;

八、UILabel 多行自動換行

關鍵是 numberOfLines = 0 加上 WordWrap:

UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(10, 100, 300, 150)];
label.text = @"Hello world! Hello world! Hello world! Hello world! Hello world!";
label.backgroundColor = [UIColor redColor];
label.textColor = [UIColor whiteColor];
label.textAlignment = UITextAlignmentCenter;
label.lineBreakMode = UILineBreakModeWordWrap;
label.numberOfLines = 0;

九、純程式碼建立按鈕,並讓元件置中

UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
button.frame = CGRectMake(0, 400, 72.0, 37.0);
[button setTitle:@"新添加的按鈕" forState:UIControlStateNormal];
button.backgroundColor = [UIColor clearColor];
button.tag = 2000;
[button addTarget:self action:@selector(buttonClicked:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:button];

// 讓任何元件直接落在父視圖正中央
label.center = self.view.center;

十、Cell 文字的美化

cell.backgroundColor = [UIColor scrollViewTexturedBackgroundColor];
cell.textLabel.font = [UIFont fontWithName:@"AmericanTypewriter" size:20.0f];
cell.textLabel.textColor = [UIColor orangeColor];
cell.textLabel.shadowColor = [UIColor whiteColor];
cell.textLabel.textAlignment = UITextAlignmentCenter;

十一、隱藏狀態列與自訂 AlertView 背景

[[UIApplication sharedApplication] setStatusBarHidden:YES animated:NO];

想換掉 UIAlertView 那層灰底,可以畫一張圖再塞進 layer.contents:

UIAlertView *theAlert = [[[UIAlertView alloc] initWithTitle:@"Atention"
                                                    message:@"I'm a Chinese!"
                                                   delegate:nil
                                          cancelButtonTitle:@"Cancel"
                                          otherButtonTitles:@"Okay", nil] autorelease];
[theAlert show];

UIImage *theImage = [UIImage imageNamed:@"loveChina.png"];
CGSize theSize = [theAlert frame].size;
UIGraphicsBeginImageContext(theSize);
[theImage drawInRect:CGRectMake(5, 5, theSize.width - 10, theSize.height - 20)];
theImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
theAlert.layer.contents = (id)[theImage CGImage];

十二、鍵盤與網路活動指示器

textField.keyboardAppearance = UIKeyboardAppearanceAlert;   // 半透明鍵盤
[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;  // 狀態列轉圈圈

十三、截取畫面

UIGraphicsBeginImageContext(CGSizeMake(200, 400));
[self.view.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage *aImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
NSData *imageData = UIImagePNGRepresentation(aImage);

十四、更換 Cell 被選取時的背景

UIView *myview = [[UIView alloc] init];
myview.frame = CGRectMake(0, 0, 320, 47);
myview.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"0006.png"]];
cell.selectedBackgroundView = myview;

十五、顯示圖片與點擊跳轉

UIImageView *myImage = [[UIImageView alloc] initWithFrame:CGRectMake(0.0f, 0.0f, 320.0f, 109.0f)];
[myImage setImage:[UIImage imageNamed:@"myImage.png"]];
myImage.opaque = YES;
[self.view addSubview:myImage];

若希望「點圖片就跳頁」,最直覺的做法是拿一個透明 UIButton 蓋在圖上,把事件綁到 button:

UIButton *imgButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 120, 120)];
[imgButton setBackgroundImage:[self.imgArray objectAtIndex:indexPath.row]
                     forState:UIControlStateNormal];
imgButton.tag = indexPath.row;
[imgButton addTarget:self action:@selector(buttonClick:) forControlEvents:UIControlEventTouchUpInside];
  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved