gpt4 book ai didi

swift - 我的委托(delegate)出了什么问题?

转载 作者:行者123 更新时间:2023-11-30 10:07:37 25 4
gpt4 key购买 nike

我是 swift 的新手,现在我正在学习 delegate。我认为我已经做了正确的事情,但仍然不起作用。

我正在做的是将数据从我的ViewController传递到TestViewController

View Controller :

protocol viewControllerDelegate: class {
func viewcontrollerdelegate(setviewcontrollerdelegate: ViewController)
}

class ViewController: UIViewController ,UITextFieldDelegate {
weak var delegate: viewControllerDelegate?

@IBAction func nextViewandDelegate(sender: AnyObject) {
self.delegate?.viewcontrollerdelegate(self)
}

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "showTestSegue" {
if let testViewController = segue.destinationViewController as? TestViewController {
testViewController.address = address.text!
testViewController.phone = phone.text!
}
}
}
}

TestViewController:

class TestViewController: UIViewController {

var name: String?
var address: String?
var phone: String?
var trydelegate: String?

override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.

let storyboard = UIStoryboard(name: "Main", bundle: nil)
let VC = storyboard.instantiateViewControllerWithIdentifier("viewcontroller") as! ViewController
VC.delegate = self
}

override func viewWillAppear(animated: Bool) {
addressLabel.text = address!
phoneLabel.text = phone!
trydelegateLabel.text = trydelegate //always nil here
}
}

extension TestViewController:viewControllerDelegate {
func viewcontrollerdelegate(setviewcontrollerdelegate: ViewController) {
self.trydelegate = setviewcontrollerdelegate.address.text!
}
}

我使用 segue 来传递地址和电话,效果很好。

但是我对委托(delegate)很不满意。谁能帮我一点忙吗?我知道这个问题对你来说有点简单。

非常感谢。

最佳答案

viewDidLoad中的TestViewController中,您创建了新对象vc,该对象与调用prepareForSegue的对象不同> 所以这就是它不起作用的原因。

要解决此问题,请从 viewDidLoad 中删除代码:

let storyboard = UIStoryboard(name: "Main", bundle: nil)
let vc = storyboard.instantiateViewControllerWithIdentifier("viewcontroller") as! ViewController
vc.delegate = self

并在prepareForSegue中添加一行:

testViewController.phone = phone.text!
// New line
self.delegate = testViewController

这应该有帮助。

关于swift - 我的委托(delegate)出了什么问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35174422/

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