1

I have an impression that ViewController usage are similar: on story board, we drag an UIViewController onto scene, then change its class type, e.g. to UIImagePickerController. (I want to make a dedicated scene for picking images)

But later I find that UIImagePickerController won't work if I directly subclass:

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

But it works only if I put an UIViewController on storyboard, then construct an UIImagePickerController programmatically:

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

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

May I know whether I missed anything in the first usage example? And is it a must to create UIImagePickerController programmatically then present it via an agent view controller (UIVIewController)?

rmaddy
  • 314,917
  • 42
  • 532
  • 579
modeller
  • 3,770
  • 3
  • 25
  • 49

1 Answers1

3
self.present(self, animated: true) 

you can not self present self, use another ViewController to present UIImagePickerController

UIImagePickerController can be used on Story board, in your code, for example

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

keep in mind that UIImagePickerController is subclass of UINavigationController

Ethan
  • 461
  • 4
  • 13
  • So, not all ViewControllers are equal (in terms of usage): i.e. UIViewController can be used directly by placement on Story board, but some view controller, e.g. UIImagePickerController, MUST use a proxy viewcontroller to present it. Am I right? – modeller Jan 02 '19 at 02:34
  • update my answer, init `TestUIImagePickerController`(subclass of UIImagePickerController) from storyboard – Ethan Jan 02 '19 at 02:53