UIImagePickerController 的一般用法
步驟 1:建立控制器,設定委託,並遵守協議
//Swift
class ImageUploadViewController: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate {
let imagePickerController = UIImagePickerController()
override func viewDidLoad() {
super.viewDidLoad()
imagePickerController.delegate = self
}
}
//Objective-C
@interface ImageUploadViewController : UIViewController <UIImagePickerControllerDelegate,UINavigationControllerDelegate> {
UIImagePickerController *imagePickerController;
}
@end
@implementation ImageUploadViewController
- (void)viewDidLoad {
[super viewDidLoad];
imagePickerController.delegate = self;
}
@end
注意:我們實際上不會實現 UINavigationControllerDelegate
中定義的任何內容,但是 UIImagePickerController
繼承自 UINavigationController
並改變了 UINavigationController
的行為。因此,我們仍然需要說我們的檢視控制器符合 UINavigationControllerDelegate
。
第 2 步:每當你需要展示 UIImagePickerController
:
//Swift
self.imagePickerController.sourceType = .Camera // options: .Camera , .PhotoLibrary , .SavedPhotosAlbum
self.presentViewController(self.imagePickerController, animated: true, completion: nil)
//Objective-C
imagePickerController.sourceType = UIImagePickerControllerSourceTypeCamera; // options: UIImagePickerControllerSourceTypeCamera, UIImagePickerControllerSourceTypePhotoLibrary, UIImagePickerControllerSourceTypeSavedPhotosAlbum
[self presentViewController:imagePickerController animated:YES completion:nil];
第 3 步:實現委託方法:
//Swift
func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) {
if let pickedImage = info[UIImagePickerControllerOriginalImage] as? UIImage {
// Your have pickedImage now, do your logic here
}
self.dismissViewControllerAnimated(true, completion: nil)
}
func imagePickerControllerDidCancel(picker: UIImagePickerController) {
self.dismissViewControllerAnimated(true, completion: nil)
}
//Objective-C
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
UIImage *pickedImage = info[UIImagePickerControllerOriginalImage];
if (pickedImage) {
//You have pickedImage now, do your logic here
}
[self dismissViewControllerAnimated:YES completion:nil];
}
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {
[self dismissViewControllerAnimated:YES completion:nil];
}