gpt4 book ai didi

ios - 如何在 IBAction 中运行委托(delegate)方法?

转载 作者:行者123 更新时间:2023-11-29 00:58:56 26 4
gpt4 key购买 nike

我在第二个 View Controller 中有一些方法。我通过委托(delegate)访问它们 - 在 func buttonSender 内部。主要目标是将按钮的 currentTitle 作为参数传递给 viewController.addNewMessage。执行此操作的最佳方法是什么?

聊天 View Controller :

protocol ReactToButtons {
func buttonSender(viewController: MyChatViewController)
}


class MyChatViewController: ChatViewController{

var delegate: ReactToButtons?

override func viewDidLoad() {
super.viewDidLoad()
delegate!.buttonSender(self)

}
}

容器 View Controller :

class ContainerViewController: UIViewController, ReactToButtons {
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
let myVC = segue.destinationViewController as! MyChatViewController
myVC.delegate = self
}

func buttonSender(viewController: MyChatViewController) {
viewController.addNewMessage(/*HERE GOES CURRENT TITLE*/)
}

@IBAction func leftButtonPressed(sender: AnyObject) {
let currentTitle = sender.currentTitle!

}

最佳答案

我已更改我的答案以适合您的代码

class ContainerViewController: UIViewController, ReactToButtons {
var delegate: MyChatViewController!
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
let myVC = segue.destinationViewController as! MyChatViewController
myVC.delegate = self
}

func buttonSender(viewController: MyChatViewController) {
delegate = viewController
}

@IBAction func leftButtonPressed(sender: AnyObject) {
let currentTitle = sender.currentTitle!
delegate!.addNewMessage(currentTitle)
}
}

关于ios - 如何在 IBAction 中运行委托(delegate)方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37273221/

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