以下整理了一批 iOS 開發中經常用到的實用小程式碼,涵蓋驗證、圖片處理、上傳、UI 操作與 GIF 解析等常見場景,方便隨時查閱。
-(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 *)imageWithImageSimple:(UIImage *)image scaledToSize:(CGSize)newSize {
UIGraphicsBeginImageContext(newSize);
[image drawInRect:CGRectMake(0, 0, newSize.width, newSize.height)];
UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return newImage;
}
透過 NSMutableURLRequest 建立 multipart/form-data 的 POST 請求,把 UIImageJPEGRepresentation 壓縮後的二進位資料拼進 body,再呼叫 NSURLConnection sendSynchronousRequest: 送出,即可將圖片上傳到伺服器。
UIImage *myImage = [UIImage imageNamed:@"1.jpg"];
[imageView setImage:myImage];
[self.view addSubview:imageView];
使用 UIImagePickerController 選擇相機或相簿來源,並在 imagePickerController:didFinishPickingMediaWithInfo: 回呼中取得選取的圖片;使用者取消則在對應的回呼中關閉。
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;
設定 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.tag = 2000;
[button addTarget:self action:@selector(buttonClicked:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:button];
若在 xib 中已建立按鈕,也可用 viewWithTag: 依 tag 取得後再綁定事件。
· 置中顯示:label.center = self.view.center;
· 隱藏狀態列:[[UIApplication sharedApplication] setStatusBarHidden:YES animated:NO];
· 截圖:建立位圖上下文後用 renderInContext: 渲染圖層,再以 UIGraphicsGetImageFromCurrentImageContext 取得圖片。
· 鍵盤透明:textField.keyboardAppearance = UIKeyboardAppearanceAlert;
· 網路活動指示器:[UIApplication sharedApplication].networkActivityIndicatorVisible(預設 NO)。
1. 加一個按鈕觸發 resignFirstResponder(較為陽春)。
2. 在背景圖片上加入 UITapGestureRecognizer,點擊時收起鍵盤。
3. 在 xib 中把 view 的 class 改為 UIControl,連接 touch down 事件。
透過 CGImageSourceCreateWithData 建立影像來源,用 CGImageSourceGetCount 取得影格數,再逐一以 CGImageSourceCreateImageAtIndex 取出各幀轉為 UIImage 加入陣列;反之,用 CGImageDestination 系列函數即可把多張圖片合成 GIF。
+ (UIImage*)imageFromView:(UIView*)view {
UIGraphicsBeginImageContextWithOptions(view.bounds.size, YES, view.layer.contentsScale);
[view.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return image;
}
注意:生成圖片的 scale 要與 view 一致,才能保證效果完全相同;使用 renderInContext: 可讓 subviews 的內容也一併呈現在圖片中。
這些片段看似零散,卻都是日常開發中反覆用到的「瑞士刀」,熟練掌握後能大幅提升開發效率。