问题
What I want to achieve:
User presses the button in the ViewController then, the color of the button placed in the container view should change its color to red.
How can I get access of the button placed in the container view, from the ViewController?
回答1:
Step by step:
- Name the segue between your view controller and container view controller.
- Add a property to your view controller which will contain the container view controller.
- In your view controller implement a method
prepareForSegue(_:sender:). - In the method check if
segue.identifierequals the identifier you specified in step 1. - If true, then save the
segue.destinationViewControllerto your property from step 2. - 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
}
}
回答2:
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.
回答3:
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
}
}
回答4:
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.
来源:https://stackoverflow.com/questions/33857210/access-container-view-child-properties-swift