Swift 3 - Prepare Segue

前端 未结 3 2109
终归单人心
终归单人心 2021-01-14 00:06

I have 3 scenes in my storyboard. My initial View Controller is a Navigation Controller, then there is a relationship root view controller to a UI ViewController (view contr

3条回答
  •  轮回少年
    2021-01-14 00:32

    I had the same issue. The logic is that one first prepares the segue (loads the UIViewController referenced by the container view), assigns it to a variable, and then uses it in viewDidLoad(). This code should work:

    Swift 4.2

    // usually an IBoutlet
    var viewController: HistoryController!
    
    override func viewDidLoad() {
        super.viewDidLoad()
    
        viewController.detailItem = barcodeInt as AnyObject
    }
    
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if segue.identifier == "HistorySegue"
        { viewController = segue.destination as! HistoryController }
    }
    

    detailItem could possibly be defined as an IBoutlet in HistoryController, it depends on the OP code. In my case, where I had two simple container views with a label each inside, this has been the final working code for the main view controller class:

    import UIKit
    
    class ViewController: UIViewController {
    
        @IBOutlet var firstView: ReusableViewController!
        @IBOutlet var secondView: ReusableViewController!
    
        override func viewDidLoad() {
            super.viewDidLoad()
            // Do any additional setup after loading the view, typically from a nib.
    
            firstView.myLabel.text = "My 1st reuse!!!"
            secondView.myLabel.text = "And that's the 2nd!"
        }
    
        override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
            if (segue.identifier == "segueFirstView")
            { firstView = (segue.destination as! ReusableViewController) }
            if (segue.identifier == "segueSecondView")
            { secondView = (segue.destination as! ReusableViewController) }
        }
    }
    

    With that I could finally change the text of the two different UILabel directly from the main controller!

    For a detailed explanation of how to use the container views one may check this S.O. answer.

提交回复
热议问题