Access container view child properties swift

落爺英雄遲暮 提交于 2019-12-03 22:21:58

Step by step:

  1. Name the segue between your view controller and container view controller.
  2. Add a property to your view controller which will contain the container view controller.
  3. In your view controller implement a method prepareForSegue(_:sender:).
  4. In the method check if segue.identifier equals the identifier you specified in step 1.
  5. If true, then save the segue.destinationViewController to your property from step 2.
  6. Now you have the container view controller stored in your property so you can do customization from your class. You should have the view controller stored in viewDidLoad() method already.

Example:

var containerViewController: YourContainerViewControllerClass?
let containerSegueName = "testSegue"
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
    if segue.identifier == containerSegueName {
        containerViewController = segue.destinationViewController as? YourContainerViewControllerClass
    }
}
Andrey Gordeev

I recommend not to rely on segue.identifier, but rather test for destination type directly:

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    super.prepare(for: segue, sender: sender)

    if let vc = segue.destination as? YourViewController {
        vc.someVariable = true
    }
}

This way you avoid mistakes with a misspelled segue name.

Swift 4, Xcode 9.4.1

var contentViewController : UIContentViewController?

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if segue.identifier == containerSegueName {
       contentViewController = segue.destination as? UIContentViewController
    }
}

Swift 3 for macOS:

// MARK: - Container View Controller

var containerViewController: ContainerViewController?

let containerSegueIdentifier = "Container Segue"

override func prepare(for segue: NSStoryboardSegue, sender: Any?) {
    if segue.identifier == containerSegueIdentifier {
        if let connectContainerViewController = segue.destinationController as? FormationViewController {
            formationViewController = connectContainerViewController
        }
    }
}

Check identifier and controller class.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!