How to pass prepareForSegue: an object

后端 未结 10 2206
北荒
北荒 2020-11-21 11:18

I have many annotations in a mapview (with rightCalloutAccessory buttons). The button will perform a segue from this mapview to a tableview

10条回答
  •  耶瑟儿~
    2020-11-21 11:43

    I came across this question when I was trying to learn how to pass data from one View Controller to another. I need something visual to help me learn though, so this answer is a supplement to the others already here. It is a little more general than the original question but it can be adapted to work.

    This basic example works like this:

    The idea is to pass a string from the text field in the First View Controller to the label in the Second View Controller.

    First View Controller

    import UIKit
    
    class FirstViewController: UIViewController {
    
        @IBOutlet weak var textField: UITextField!
    
        // This function is called before the segue
        override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
    
            // get a reference to the second view controller
            let secondViewController = segue.destinationViewController as! SecondViewController
    
            // set a variable in the second view controller with the String to pass
            secondViewController.receivedString = textField.text!
        }
    
    }
    

    Second View Controller

    import UIKit
    
    class SecondViewController: UIViewController {
    
        @IBOutlet weak var label: UILabel!
    
        // This variable will hold the data being passed from the First View Controller
        var receivedString = ""
    
        override func viewDidLoad() {
            super.viewDidLoad()
    
            // Used the text from the First View Controller to set the label
            label.text = receivedString
        }
    
    }
    

    Remember to

    • Make the segue by control clicking on the button and draging it over to the Second View Controller.
    • Hook up the outlets for the UITextField and the UILabel.
    • Set the first and second View Controllers to the appropriate Swift files in IB.

    Source

    How to send data through segue (swift) (YouTube tutorial)

    See also

    View Controllers: Passing data forward and passing data back (fuller answer)

提交回复
热议问题