从子视图启动时,ImagePickerController立即被解雇

时间:2017-08-14 08:50:49

标签: ios swift presentmodalviewcontroller

我正在尝试以模态方式呈现ImagePickerController。触发当前动作的我的按钮位于主视图的子视图内。 按下按钮时,ImagePicker视图会立即显示和解除。 我尝试使用另一个位于主视图中的按钮,并且工作正常。

我的按钮操作代码:

@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            
    }
}

委托方法:

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)
}

我的观点层次结构:

enter image description here

我缺少什么?

1 个答案:

答案 0 :(得分:0)

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)

            }
}