最简单的方法是在简单的alertView中使用UIImagePickerController。
例如,您希望某人点击他们的个人资料图片并能够从他们的相机或照片库设置新图像。
@IBAction func btnProfilePicTap(sender: AnyObject) {
let picker = UIImagePickerController()
picker.delegate = self
let alert = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet)
alert.addAction(UIAlertAction(title: "Camera", style: .default, handler: {
action in
picker.sourceType = .camera
self.present(picker, animated: true, completion: nil)
}))
alert.addAction(UIAlertAction(title: "Photo Library", style: .default, handler: {
action in
picker.sourceType = .photoLibrary
self.present(picker, animated: true, completion: nil)
}))
alert.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil))
self.present(alert, animated: true, completion: nil)
}
然后只需添加委托即可完成。
extension ProfileViewController: UIImagePickerControllerDelegate, UINavigationControllerDelegate {
func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage!, editingInfo: [NSObject : AnyObject]!) {
//use image here!
dismiss(animated: true, completion: nil)
}
func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
dismiss(animated: true, completion: nil)
}
}
抱歉,这个例子是快速的,但我希望它仍然有帮助。
编辑:针对 Swift 5 进行了更新。