我正在尝试以模态方式呈现 ImagePickerController。我触发当前操作的按钮位于主视图的 subview 内。 按下按钮时,ImagePicker View 将立即显示并关闭。 我对主视图中的另一个按钮进行了相同的尝试,并且工作正常。
我的按钮操作代码:
@IBAction func pressUploadProfilePhoto(_ sender: Any) {
picker.allowsEditing = false
picker.sourceType = .photoLibrary
present(picker, animated: true, completion: nil)
}
类减速度:
class ProfileVC: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate {
let imagePicker = UIImagePickerController()
override func viewDidLoad() {
super.viewDidLoad()
imagePicker.delegate = self
}
}
委托(delegate)方法:
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
if let pickedImage = info[UIImagePickerControllerOriginalImage] as? UIImage {
profilePicImg.contentMode = .scaleAspectFill
profilePicImg.image = pickedImage
}
self.dismiss(animated: true, completion: nil)
}
func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
dismiss(animated: true, completion: nil)
}
我的 View 层次结构:
我错过了什么?
最佳答案
Please Try the below code, may be your problem get resolved ->
1) Firstly add these Delegates in your Class.
class XYZ: UIActionSheetDelegate, UIImagePickerControllerDelegate, UINavigationControllerDelegate
2) Create a variable ->
let imagePicker = UIImagePickerController()
3) Set imagePicker delegate in viewDidLoad
override func viewDidLoad() {
super.viewDidLoad()
imagePicker.delegate = self
}
4) Write Delegate Methods for UIImagePicker
// MARK: - ImageView Controller Delegate Methods
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
if let pickedImage = info[UIImagePickerControllerOriginalImage] as? UIImage {
imageviewProfile.contentMode = .scaleToFill
imageviewProfile.image = pickedImage
}
dismiss(animated: true, completion: nil)
}
func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
dismiss(animated: true, completion: nil)
}
5) Now your Action Method ->
@IBAction func pressUploadProfilePhoto(_ sender: Any) {
if UIImagePickerController.isSourceTypeAvailable(.photoLibrary) {
imagePicker.allowsEditing = false
imagePicker.sourceType = UIImagePickerControllerSourceType.photoLibrary
imagePicker.modalPresentationStyle = .fullScreen
present(imagePicker, animated: true, completion: nil)
}
}
关于ios - 从 subview 启动时 ImagePickerController 立即被解雇,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45670729/