做新界面的時候翻回以前的程式碼,順手把幾個常用小功能整理成筆記,第一篇就談「讓使用者更換大頭貼」。
這個畫面需要同時採用三個協定:
@interface UserStaticProfileViewController : UIViewController
<UIActionSheetDelegate,
UIImagePickerControllerDelegate,
UINavigationControllerDelegate>
@end
分工是:UIActionSheetDelegate 處理「拍照/相簿」的選擇,UIImagePickerControllerDelegate 接收使用者挑好的圖片,UINavigationControllerDelegate 則是 UIImagePickerController 的必要搭配。
同一個畫面上往往會有好幾個 action sheet(這裡有「換大頭貼」與「登出」兩個)。實作的做法是用 tag 把它們區分開:
#define kLogoutActionSheetTag 500 #define kPhotoActionSheetTag 501
UIImageView 預設不接收使用者互動,所以要手動打開 userInteractionEnabled,再掛上手勢:
avartView = [[UIImageView alloc] initWithFrame:CGRectMake(125.0, 45.0, 70.0, 70.0)];
avartView.layer.cornerRadius = avartView.frame.size.height / 2; // 變成正圓
avartView.layer.masksToBounds = YES;
avartView.userInteractionEnabled = YES; // 關鍵:預設是 NO
[avartView setContentMode:UIViewContentModeScaleAspectFill];
[avartView setClipsToBounds:YES];
// 陰影與白邊
avartView.layer.shadowColor = [UIColor whiteColor].CGColor;
avartView.layer.shadowOffset = CGSizeMake(4.0, 4.0);
avartView.layer.shadowOpacity = 0.5;
avartView.layer.shadowRadius = 2.0;
avartView.layer.borderColor = [UIColor whiteColor].CGColor;
avartView.layer.borderWidth = 2.0f;
[self.view addSubview:avartView];
// 掛上手勢
UITapGestureRecognizer *singleTap =
[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(setPhoto:)];
[avartView addGestureRecognizer:singleTap];
- (void)actionSheet:(UIActionSheet *)actionSheet
clickedButtonAtIndex:(NSInteger)buttonIndex {
if (actionSheet.tag == kPhotoActionSheetTag) {
if (buttonIndex == 0) {
// 拍照前必須先確認裝置有相機
if ([UIImagePickerController isSourceTypeAvailable:
UIImagePickerControllerSourceTypeCamera]) {
[self takePhoto];
} else {
// 提示不支援
}
}
if (buttonIndex == 1) {
if ([UIImagePickerController isSourceTypeAvailable:
UIImagePickerControllerSourceTypePhotoLibrary]) {
[self choosePhoto];
} else {
// 提示不支援
}
}
}
// ... 其他 tag 的處理,例如登出確認
}
這裡有個容易被忽略的防禦寫法:isSourceTypeAvailable: 必須在開啟相機或相簿之前檢查。在模擬器或沒有相機的裝置上直接指定 sourceType,是會出問題的。
- (void)takePhoto {
if (!_imagepicker) _imagepicker = [[UIImagePickerController alloc] init];
_imagepicker.delegate = self;
_imagepicker.sourceType = UIImagePickerControllerSourceTypeCamera;
_imagepicker.allowsEditing = YES; // 允許裁切
[self presentModalViewController:_imagepicker animated:YES];
}
- (void)choosePhoto {
if (!_imagepicker) _imagepicker = [[UIImagePickerController alloc] init];
_imagepicker.delegate = self;
_imagepicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
_imagepicker.allowsEditing = YES;
[self presentModalViewController:_imagepicker animated:YES];
}
- (void)imagePickerController:(UIImagePickerController *)picker
didFinishPickingMediaWithInfo:(NSDictionary *)info {
// 從相機進來時狀態列可能被隱藏,記得還原
[[UIApplication sharedApplication] setStatusBarHidden:NO
withAnimation:UIStatusBarAnimationNone];
// 開啟了 allowsEditing,所以取編輯後的版本
pickedImage = [info valueForKey:UIImagePickerControllerEditedImage];
// 裁成正方形,避免上傳後頭像變形
CGSize imgSize = pickedImage.size;
if (imgSize.width > imgSize.height) imgSize.height = imgSize.width;
else imgSize.width = imgSize.height;
pickedImage = [UIImage createImageWithSize:imgSize FromImage:pickedImage];
// 上傳放到背景執行緒,避免卡住 UI
[self performSelectorInBackground:@selector(startUploadImage:)
withObject:pickedImage];
[_imagepicker dismissModalViewControllerAnimated:YES];
}
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {
[picker dismissModalViewControllerAnimated:YES];
}
- (void)startUploadImage:(UIImage *)photoImage {
_headerImage = photoImage;
[self uploadAvartReceive];
}
- (void)uploadAvartReceive {
avartView.image = _headerImage;
[MBProgressHUD showWithLabel:NSLocalizedString(@"success", nil)
withView:self.view];
}
進入畫面時,先試著從本地檔案讀回上次的頭像;讀不到就退回預設圖:
if (_userProfile) {
avartURL = [NSString stringWithString:_userProfile.avatar];
NSString *avatarPath = [[FileManager getClassInstance]
getAvatarMessageFolder:loginUserJid
withImageUrl:_userProfile.avatar];
NSData *imageData = [NSData dataWithContentsOfFile:avatarPath];
if (imageData) {
UIImage *image = [UIImage imageWithData:imageData];
avartView.image = [image roundedCornerImage:10 borderSize:3];
} else {
avartView.image = [UIImage imageNamed:@"profileIcon.png"];
}
}
把整個流程走過一遍,有幾處值得在實際專案中調整:
· presentModalViewController:animated: 與 dismissModalViewControllerAnimated: 都已被 deprecated,新專案應改用 presentViewController:animated:completion: 與 dismissViewControllerAnimated:completion:。
· 圖片裁切與上傳之間,建議先壓縮再傳。原圖直接上傳在行動網路上很浪費流量。
· 上傳成功後的 UI 更新,嚴格說應該回到主執行緒執行,performSelectorInBackground 裡直接改 avartView.image 並不保險。
· 使用者取消上傳或上傳失敗時,畫面應該保留原圖,不要讓 UI 停在中間狀態。