iOS 開發中有許多高頻重複的功能模組。本文精選 11 個實戰常用的代碼片段,涵蓋輸入驗證、圖片處理、網路上傳、系統相冊互動、視圖控制器跳轉、導航欄配置、標籤自動換行、按鈕動態創建、視圖置中等,均經實測可直接專案中使用。
- (BOOL)isValidateEmail:(NSString *)email {
// RFC 5322 簡化版正則,涵蓋常見格式
NSString *emailRegex = @"[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,}";
NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailRegex];
return [emailTest evaluateWithObject:email];
}
注意:原文正則限制尾碼 2-4 字元,新頂級域名可超過 4 字 (如 .technology),建議改為 {2,}。
- (UIImage *)imageWithImageSimple:(UIImage *)image scaledToSize:(CGSize)newSize {
UIGraphicsBeginImageContextWithOptions(newSize, NO, 0.0); // 支援 Retina
[image drawInRect:CGRectMake(0, 0, newSize.width, newSize.height)];
UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return newImage;
}
// 使用範例
UIImage *thumb = [self imageWithImageSimple:originalImage scaledToSize:CGSizeMake(210, 210)];
進階:需壓縮檔案大小 (如 < 1MB) 時,使用 UIImageJPEGRepresentation(image, quality) 迭代調整 quality (0.0~1.0)。
- (IBAction)uploadButton:(id)sender {
UIImage *image = [UIImage imageNamed:@"1.jpg"];
NSData *imageData = UIImageJPEGRepresentation(image, 0.5); // 壓縮品質 0.5
NSLog(@"檔案大小: %lu bytes", (unsigned long)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 = @"----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]];
// Content-Disposition
[body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"userfile\"; filename=\"2.png\"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
// Content-Type
[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];
// 同步請求 (僅示範,生產環境請用非同步)
NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
NSString *returnString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];
NSLog(@"伺服器回應: %@", returnString);
}
生產環境建議:使用 NSURLSession + dataTaskWithRequest:completionHandler: 非同步上傳,或採用 AFNetworking/Alamofire 成熟網路庫。
UIImage *myImage = [UIImage imageNamed:@"1.jpg"];
UIImageView *imageView = [[UIImageView alloc] initWithImage:myImage];
imageView.frame = CGRectMake(50, 100, myImage.size.width, myImage.size.height);
[self.view addSubview:imageView];
#pragma mark - 開啟相冊/相機
- (void)openImagePicker {
UIImagePickerControllerSourceType sourceType = UIImagePickerControllerSourceTypeCamera;
if (![UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
}
UIImagePickerController *picker = [[UIImagePickerController alloc] init];
picker.delegate = self;
picker.allowsEditing = YES; // 允許裁剪
picker.sourceType = sourceType;
[self presentViewController:picker animated:YES completion:nil];
}
#pragma mark - UIImagePickerControllerDelegate
- (void)imagePickerController:(UIImagePickerController *)picker
didFinishPickingMediaWithInfo:(NSDictionary *)info {
[picker dismissViewControllerAnimated:YES completion:nil];
UIImage *image = info[UIImagePickerControllerEditedImage]; // 裁剪後圖片
// 或 info[UIImagePickerControllerOriginalImage] 原圖
[self performSelector:@selector(handleSelectedImage:) withObject:image afterDelay:0.1];
}
- (void)handleSelectedImage:(UIImage *)image {
NSLog(@"選取圖片: %@", image);
UIImageView *iv = [[UIImageView alloc] initWithImage:image];
iv.frame = CGRectMake(0, 0, image.size.width, image.size.height);
[self.view addSubview:iv];
// 後續處理:上傳、識別、濾鏡等
[self performSelectorInBackground:@selector(processImage:) withObject:image];
}
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {
[picker dismissViewControllerAnimated:YES completion:nil];
}
NextViewController *nextVC = [[NextViewController alloc] initWithNibName:@"NextViewController" bundle:nil];
[self presentViewController:nextVC animated:YES completion:nil];
// iOS 8+ 推薦使用 Storyboard + Segue 或程式化 initWithStoryboard
UIBarButtonItem *rightButton = [[UIBarButtonItem alloc]
initWithTitle:@"右邊" style:UIBarButtonItemStyleDone target:self action:@selector(clickRightButton)];
self.navigationItem.rightBarButtonItem = rightButton;
// 自定義 View 做按鈕 (支援圖片+文字、Badge 等)
UIButton *customBtn = [UIButton buttonWithType:UIButtonTypeCustom];
[customBtn setImage:[UIImage imageNamed:@"icon"] forState:UIControlStateNormal];
[customBtn setTitle:@"編輯" forState:UIControlStateNormal];
[customBtn sizeToFit];
[customBtn addTarget:self action:@selector(editAction) forControlEvents:UIControlEventTouchUpInside];
self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:customBtn];
// 整個導航控制器隱藏
self.navigationController.navigationBarHidden = YES;
// 或單一視圖控制器
self.navigationController.navigationBar.hidden = YES; // 同義
// 動畫隱藏/顯示
[self.navigationController setNavigationBarHidden:YES animated:YES];
UIView *footerView = [[UIView alloc] initWithFrame:CGRectMake(10, 100, 300, 180)];
UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(10, 0, 280, 0)]; // 高度設 0
label.text = @"Hello world! Hello world! Hello world! Hello world! Hello world! Hello world!";
label.backgroundColor = [UIColor redColor];
label.textColor = [UIColor whiteColor];
label.textAlignment = NSTextAlignmentCenter;
label.numberOfLines = 0; // 0 代表無限制行數
label.lineBreakMode = NSLineBreakByWordWrapping; // 單字換行
[label sizeToFit]; // 關鍵:根據內容自適應高度
[footerView addSubview:label];
CGRect frame = CGRectMake(0, 400, 72, 37);
UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect]; // 或 UIButtonTypeSystem / Custom
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];
// 事件處理
- (void)buttonClicked:(UIButton *)sender {
NSLog(@"按鈕 %ld 被點擊", (long)sender.tag);
}
// 任意 view 置中於 self.view
subview.center = self.view.center;
// 若使用 Auto Layout (推薦)
[subview.translatesAutoresizingMaskIntoConstraints = NO];
[NSLayoutConstraint activateConstraints:@[
[subview.centerXAnchor constraintEqualToAnchor:self.view.centerXAnchor],
[subview.centerYAnchor constraintEqualToAnchor:self.view.centerYAnchor]
]];
NSURLSession / Alamofire / AFNetworkingSDWebImage / Kingfisher (Swift)Masonry (Obj-C) / SnapKit (Swift) / 原生 Anchor APIInfo.plist 聲明 NSCameraUsageDescription、NSPhotoLibraryUsageDescription