简译自 UIImagePickerController in Swift,原文by angeliphonedev

在iOS开发中,我们的app不免需要用户从相册中选择相片并且对其进行操作。
在Swift中这是极其简单的。我们只需要使用UIImagePickerController这个类即可。
使用之前我们需要使当前的ViewController类继承两个Delegate类:

        class TheViewController: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate

继承了UIImagePickerControllerDelegateUINavigationControllerDelegate之后,现在的ViewController已经具备了基本条件,下面就是代码的编写了。
在某一个按钮的Action Handler中写下如下代码

var imagePickerController = UIImagePickerController()
imagePickerController.delegate = self
imagePickerController.sourceType = UIImagePickerControllerSourceType.SavedPhotosAlbum
imagePickerController.allowsEditing = true
self.presentViewController(imagePickerController, animated: true, completion: { imageP in})

Pick Image from Album

现在我们可以开启图片选择界面了,那么选择来的图片怎么拿到手呢?
利用下面的代码片段即可。

/*Image Picker Controller Delegate*/
func imagePickerController(picker: UIImagePickerController!, didFinishPickingImage image: UIImage!, editingInfo: NSDictionary!) {
    let selectedImage : UIImage = image
}

selectedImage就是我们需要的UIImage对象了。
当然 最后不要忘记了在imagePickerController函数当中加入

self.dismissViewControllerAnimated(true, completion: nil)

来关闭图片选择窗口。

COOL!