Search code examples
iosswiftcontrolleraddsubview

Swift 3: Buttons not working on controller added as subview


I recently upgraded to Xcode 8.0/Swift 3.

I'm adding a controller to pick images as a subview to another controller, and for some reason the buttons on the controller added as a subview won't work. This was no problem before.

Here's the code:

let pickerController = DKImagePickerController()


 override func viewDidLoad() {
    super.viewDidLoad()

    pickerController.defaultSelectedAssets = self.assets

    pickerController.didSelectAssets = { (assets: [DKAsset]) in
        print("didSelectAssets")
    }

    self.addChildViewController(pickerController)
    self.view.addSubview(pickerController.view)
    pickerController.didMove(toParentViewController: self)
}

Any ideas? All the answers I find suggest this should work :(

The callback (didSelectAssets) works find if I just present the pickerController using

self.present(pickerController, animated: true) {}

Solution

  • The DKImagePickerController appears to be designed only for presenting as a view controller, not for adding as a childVC and subview to your current view. So, because you didn't present it, it fails to make the callback.

    If that's how you want to display it, you'll need to make some edits to DKImagePickerController itself.

    A quick test of changing the done() func in DKImagePickerController.swift to this:

    open func done() {
    
        if self.presentingViewController == nil {
            self.didSelectAssets?(self.selectedAssets)
        }
        else
        {
    
            self.presentingViewController?.dismiss(animated: true, completion: {
                self.didSelectAssets?(self.selectedAssets)
            })
    
        }
    }
    

    will result in your callback func being called:

    pickerController.didSelectAssets = { (assets: [DKAsset]) in
        print("didSelectAssets")
    }
    

    From there, however, you'll have to do your own coding for removing the subview, handling the selections, etc. You may also need to modify some other functions inside DKImagePickerController - I just did a quick test to get the callback working.