gpt4 book ai didi

ios - 在没有 segue 的 2x ViewController 之间传递信息时,Delegate 始终为 nil

转载 作者:塔克拉玛干 更新时间:2023-11-02 22:05:49 26 4
gpt4 key购买 nike

我是 Xcode/Swift 编程的新手,我遇到了一个小问题。

我想使用委托(delegate)将信息从一个 ViewController 发送到第二个 ViewController,而不使用 segue。我阅读了很多相关内容,发现最常见的解决方案是在 ViewDidLoad 中使用“instance”.delegate = self,但它对我不起作用。

-- 应用的定义--

这很容易。在第一个 ViewController 上,我有一个按钮和一个标签。该按钮打开第二个 ViewController,它有一个 textField 和一个 Button。 Button 将 textField 中的内容发送到第一个 ViewController 以更新 Label。

-- 代码--

这是第一个 ViewController 的代码:

class ViewController: UIViewController, clickedButtonDelegate {

@IBOutlet weak var Label: UILabel!

func didClickedButton(text: String) {
Label.text = text
}

var secondView = SecondViewController()

override func viewDidLoad() {
super.viewDidLoad()
secondView.delegate = self
}
}

这是第二个 ViewController 的代码:

protocol clickedButtonDelegate {
func didClickedButton(text: String)
}

class SecondViewController: UIViewController {

@IBOutlet weak var introducedText: UITextField!

var delegate : clickedButtonDelegate!

@IBAction func sendData(_ sender: Any) {
if delegate != nil {
let information:String = introducedText.text!
delegate!.didClickedButton(text: information)
dismiss(animated: true, completion: nil)
self.navigationController?.popViewController(animated: true)
}
}
}

使用此代码没有任何反应,因为在 SecondViewController 中委托(delegate)始终为 nil。

你能帮忙吗?

提前致谢!

最佳答案

其实我原来的代码比较复杂。我试图通过一个更简单的练习来“减少问题”,以便更好地理解如何在使用和不使用 Segues 的情况下传递信息。

我正在将两个 ViewController 与一个 Segue 连接起来(见图)。

Layout

到目前为止,我发现了两种在这里有效的信息传递方式:

  1. Segue:通过使用 Segue 连接两个 ViewController 并使用 prepare(for segue),如下例所示,然后使用协议(protocol)函数:

    //This piece of code goes inside the first ViewController
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if segue.identifier == "showSecondView" {
    let secondView: SecondViewController = segue.destination as! SecondViewController
    secondView.delegate = self
    }
    }
  2. 实例化:通过创建第一个 ViewController 的新实例并使用我需要的来自第二个 View Controller 的信息,如示例代码所示:

    //This piece of code goes inside the second ViewController
    @IBAction func sendData(_ sender: Any) {
    let text_to_pass = introducedText.text

    let firstVC = storyboard?.instantiateViewController(withIdentifier: "GetData") as! ViewController
    self.present(firstVC, animated: true)
    firstVC.Label.text = text_to_pass
    }

这两个选项在这里都可以,但我想了解为什么上面的代码不起作用。我读了很多文章,大多数人都在 ViewDidLoad 中使用 secondView.delegate = self 并像魅力一样工作。

我做错了什么?

关于ios - 在没有 segue 的 2x ViewController 之间传递信息时,Delegate 始终为 nil,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47735120/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com