您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 訊息 >> iOS 相關資訊

iPhone 開發常識集錦:從基礎判斷到圖片處理

編輯:iOS 相關資訊

這篇文章把日常開發中反覆用到的零碎代碼片段彙集在一起,涵蓋運行時判斷、通知、圖片壓縮與上傳、相冊操作、視圖跳轉等常見場景,適合當作速查手冊。

一、運行時與延遲執行

檢查對象是否實現某方法

if ([obj respondsToSelector:@selector(someMethod)]) { /* ... */ }

延遲異步執行

[self performSelector:@selector(someMethod) withObject:nil afterDelay:1.0];

模擬器沙盒路徑

舊版模擬器的 Documents 目錄形如:

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

實際開發中更推薦通過 NSHomeDirectory() 動態拼接,避免硬編碼路徑。

二、自定義通知

發送

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

接收

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

三、郵箱格式校驗

- (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 *yourImage = [self imageWithImageSimple:image scaledToSize:CGSizeMake(210.0, 210.0)];

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

這種做法改變的是尺寸。若要調整文件體積,更直接的方式是控制 UIImageJPEGRepresentation 的壓縮質量參數。

五、圖片上傳

- (IBAction)uploadButton:(id)sender {
    UIImage *image = [UIImage imageNamed:@"1.jpg"];
    NSData *imageData = UIImageJPEGRepresentation(image, 0.5);
    NSLog(@"字節數:%i", [imageData length]);

    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";
    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 stringWithFormat:
        @"Content-Disposition: form-data; name=\"userfile\"; filename=\"2.png\"\r\n"]
                      dataUsingEncoding:NSUTF8StringEncoding]];
    [body appendData:[[NSString stringWithFormat:@"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];

    NSData *returnData = [NSURLConnection sendSynchronousRequest:request
                                             returningResponse:nil
                                                         error:nil];
    NSString *returnString = [[NSString alloc] initWithData:returnData
                                                  encoding:NSUTF8StringEncoding];
    NSLog(@"測試輸出:%@", returnString);
}

multipart 協議的關鍵是 boundary 必須在 Content-Type 與 body 中完全一致,且 body 首尾的 -- 標記不能漏。另外這裡用的是同步請求,會阻塞主線程,正式項目請改用 NSURLSession 異步方式。

六、相冊與相機操作

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

選擇完成

- (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)selectPic:(UIImage *)image {
    imageView = [[UIImageView alloc] initWithImage:image];
    imageView.frame = CGRectMake(0, 0, image.size.width, image.size.height);
    [self.view addSubview:imageView];
    [self performSelectorInBackground:@selector(detect:) withObject:nil];
}

取消選擇

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

這裡用 performSelector:withObject:afterDelay: 延遲刷新,是為了避開 dismiss 動畫與佈局衝突導致的閃動。

七、視圖與控件小技巧

跳轉到下一個界面

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 多行自動換行

UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(10, 100, 300, 150)];
label.backgroundColor = [UIColor redColor];
label.textColor = [UIColor whiteColor];
label.textAlignment = NSTextAlignmentCenter;
label.lineBreakMode = NSLineBreakByWordWrapping;
label.numberOfLines = 0;   // 0 表示不限行數
[self.view addSubview:label];

代碼創建按鈕

UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
button.frame = CGRectMake(0, 400, 72.0, 37.0);
button.backgroundColor = [UIColor clearColor];
button.tag = 2000;
[self.view addSubview:button];

讓控件居中

label.center = self.view.center;

cell 文字樣式

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

隱藏狀態欄

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

自定義 AlertView 背景

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"];
theImage = [theImage stretchableImageWithLeftCapWidth:0 topCapHeight:0];
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];

註:iOS 7 之後 stretchableImageWithLeftCapWidth:topCapHeight: 已改名為 resizableImageWithCapInsets:,UIAlertView 也早已被 UIAlertController 取代。

鍵盤透明

textField.keyboardAppearance = UIKeyboardAppearanceAlert;

網絡活動指示器

[UIApplication sharedApplication].networkActivityIndicatorVisible = YES; // 默認 NO

截取屏幕

UIGraphicsBeginImageContext(CGSizeMake(200, 400));
[self.view.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage *aImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
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, 0, 320, 109)];
[myImage setImage:[UIImage imageNamed:@"myImage.png"]];
myImage.opaque = YES;
[self.view addSubview:myImage];

點擊圖片跳轉:用帶背景圖的按鈕

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

八、一點提醒

這份代碼集寫於 iOS 6、7 的年代,其中不少 API 已被廢棄:presentModalViewController:animated: 應改為 presentViewController:animated:completion:,UITextAlignmentCenter 改為 NSTextAlignmentCenter,UILineBreakModeWordWrap 改為 NSLineBreakByWordWrapping,MRC 的 autorelease 在 ARC 下也不需要了。當作思路參考即可,具體 API 請以當前 SDK 為準。

  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved