UIImagePickerController可以直接在故事板上使用吗?

时间:2019-01-02 02:16:01

标签: ios swift uiimagepickercontroller

我的印象是ViewController的用法很相似:在故事板上,我们将UIViewController拖到场景上,然后更改其类类型,例如到UIImagePickerController。 (我想制作一个专门的场景来拾取图像)

但是后来我发现如果直接子类化,UIImagePickerController将不起作用:

class TestUIImagePickerController: UIImagePickerController, UIImagePickerControllerDelegate, UINavigationControllerDelegate {

    override func viewDidLoad() {
        super.viewDidLoad()
        self.sourceType = .photoLibrary
        self.delegate = self
        // self.present(self, animated: true) // either comment it out or not, both way won't work. 
    }

但是只有在我将UIViewController放在情节提要上然后以编程方式构造UIImagePickerController时,它才有效:

class SecondTestUIImagePickerController: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate {
    override func viewDidLoad() {
        super.viewDidLoad()

        let picker = UIImagePickerController()
        picker.sourceType = .photoLibrary
        picker.delegate = self
        self.present(picker, animated: true)
    } 

我可以知道在第一个用法示例中是否错过了任何内容吗?是否必须以编程方式创建UIImagePickerController然后通过代理程序视图控制器(UIVIewController)呈现它?

1 个答案:

答案 0 :(得分:3)

self.present(self, animated: true) 

您不能self出示self,不能使用另一个ViewController出示UIImagePickerController

UIImagePickerController可用于故事板上的代码中,例如

class SecondTestUIImagePickerController: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate {
    override func viewDidLoad() {
        super.viewDidLoad()
        let sb = UIStoryboard(name: "ImagePickerStoryboard", bundle: nil)
        let picker = sb.instantiateViewControllerWithIdentifier("ImagePicker") as! TestUIImagePickerController
        self.present(picker, animated: true)
}

请记住,UIImagePickerControllerUINavigationController的子类