【问题标题】:Attempting to pass data from one viewcontroller to another using segues尝试使用 segue 将数据从一个视图控制器传递到另一个视图控制器
【发布时间】:2019-06-16 14:05:37
【问题描述】:

我设置了两个视图控制器并设置了 segue 连接。我正在尝试将数据从一个 VC 传递到另一个。使用下面的代码并使用 func 覆盖工作。我想要做的只是让覆盖函数准备在按下按钮时触发,当我将覆盖函数代码粘贴到按钮操作中时,它不起作用 - 第一个 VC 上的标签不会更新 - 它保持默认我设置的值。

第一个 ViewController 代码:

    var testLabel1:String = "default"

    @IBOutlet weak var testLabel: UILabel!

    override func viewDidLoad() {
        super.viewDidLoad()
        testLabel?.text = testLabel1
        // Do any additional setup after loading the view.
    }

第二个 ViewController 代码:

override func prepare(for segue: UIStoryboardSegue, sender: Any?)
    {
        if segue.destination is ViewController
        {
            let vc = segue.destination as? ViewController
            vc?.testLabel1 = "Success"
        }
    }

我尝试过的按钮操作

    @IBAction func actionBtn(_ sender: Any) {
        func prepare(for segue: UIStoryboardSegue, sender: Any?)
        {
            if segue.destination is ViewController
            {
                let vc = segue.destination as? ViewController
                vc?.testLabel1 = "Success"
            }
        }
    }

【问题讨论】:

    标签: swift xcode segue


    【解决方案1】:

    你需要用performSegue触发它

    class FirstVc:UIViewController {
    
        @IBOutlet weak var lbl:UILabel!
    
        @IBAction func goToSecond(_ sender: Any) {
            self.performSegue(withIdentifier:"YourSegueName",sender:nil)
        }
    
        override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
            if segue.identifier == "YourSegueName" {
                let vc = segue.destination as! SecondVC
                vc.testLabel1 = "Success"
            }
        }
    
        func setData(_ str:String){
            self.lbl.text = str
    
        }
    
    }
    
    class SecondVC:UIViewController {
    
        var testLabel1 = ""
        weak var delegate:FirstVc?
    
        func goBack() {
            self.delegate?.setData("FromSecond")
            self.dismiss(animated: true, completion: nil)
        }
    
    
    }
    

    【讨论】:

    • 感谢您这么快的回答。稍后会试试这个。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-11-27
    • 2020-08-13
    相关资源
    最近更新 更多