从子视图加载UIImagePickerController

时间:2017-05-23 01:22:25

标签: ios swift uiimagepickercontroller subview

我正在尝试从自定义子视图加载UIImagePickerController的实例。由于某种原因,它不起作用,并一直给我:

<UIImagePickerController: 0x7fde7282bc00> on <UIViewController: 0x7fde6f507f00> whose view is not in the window hierarchy!

以下是我的代码的框架:

查看控制器

let subview = SubView()
// Subview params...
subview.parent = self
self.view.addSubview(subview)

子视图

class SubView: UIView, UIImagePickerControllerDelegate, UINavigationControllerDelegate {

    let imagePicker = UIImagePickerController()

    var parent = UIViewController()

    override func draw(_ rect: CGRect) {
        imagePicker.delegate = self
        let add = UIButton()
        // add params...
        add.addTarget(self, action: #selector(addImg(_:)), for: .touchUpInside)
        self.addSubview(add)
    }

    func addImg(_ sender: UIButton) {

        imagePicker.allowsEditing = false
        imagePicker.sourceType = .photoLibrary

        parent.present(imagePicker, animated: true, completion: nil)

    }

    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {

        if let pickedImage = info[UIImagePickerControllerOriginalImage] as? UIImage {
            // Do stuff with image

        }

    }

}

关于如何让这个工作的任何想法?

1 个答案:

答案 0 :(得分:0)

您可以使用rootController获取最新UIApplication。这是我的工作代码。它将找到rootController并检查它是否为UINavigationControllerUIViewController

的类型
if let rootController = UIApplication.shared.keyWindow?.rootViewController {

    if rootController is UINavigationController {
        if let navigationController = rootController as? UINavigationController {
            if let topViewController = navigationController.topViewController {
                topViewController.present(alert, animated: true, completion: nil)
            }
        }
    }
    else {
        // is a view controller
        rootController.present(alert, animated: true, completion: nil)
    }
}