为什么这个委托模式不起作用?在DelegateViewController中选择一个Button后,我想在第二个ViewController(标签出口)中显示name属性
我已完成以下步骤:
在" Boss"中创建协议ViewController - > DelegateViewController
将我的功能分配给此协议 - > selectedButton
DelegateViewController:
import UIKit
protocol SelectionDelegate {
func selectedButton(name: String)
}
class DelegateViewController: UIViewController {
var selectionButtonDelegate: SelectionDelegate!
@IBAction func bayernButton(_ sender: UIButton) {
selectionButtonDelegate.selectedButton(name: "Bayern")
}
@IBAction func dortmundButton(_ sender: UIButton) {
selectionButtonDelegate.selectedButton(name: "Dortmund")
}
}
的ViewController:
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var selectedButton: UILabel!
let model = DelegateViewController()
override func viewDidLoad() {
super.viewDidLoad()
model.selectionButtonDelegate = self
}
}
extension ViewController: SelectionDelegate {
func selectedButton(name: String) {
selectedButton.text = name
}
}
答案 0 :(得分:0)
通过查看代码问题,您的实现看起来很不错
let model = DelegateViewController()
您正在创建DelegateViewController
的新实例,但您必须从DelegateViewController
控制器的其他实例中单击按钮。
您可能需要获取model
的正确实例,而不是创建新实例,或者应该从新创建的View Controller实例中点击按钮。
示例:可能需要执行类似
的操作class ViewController: UIViewController {
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
super.prepare(for: segue, sender: sender)
if let navigationController = segue.destination as? DelegateViewController {
selectionButtonDelegate = self = self
}
}
}
答案 1 :(得分:-2)
您没有将selectionButtonDelegate分配给当前活动的DelegateViewController。修改代码以访问DelegateViewController的当前实例。
import UIKit
protocol SelectionDelegate {
func selectedButton(name: String)
}
class DelegateViewController: UIViewController {
static weak var shared: DelegateViewController!
weak var selectionButtonDelegate: SelectionDelegate!
override func viewDidLoad() {
super.viewDidLoad()
DelegateViewController.shared = self
}
@IBAction func bayernButton(_ sender: UIButton) {
selectionButtonDelegate.selectedButton(name: "Bayern")
}
@IBAction func dortmundButton(_ sender: UIButton) {
selectionButtonDelegate.selectedButton(name: "Dortmund")
}
}
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var selectedButton: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
DelegateViewController.shared.selectionButtonDelegate = self
}
}
extension ViewController: SelectionDelegate {
func selectedButton(name: String) {
selectedButton.text = name
}
}
同样在大多数情况下,在Swift中声明委托变量之前使用weak来避免内存泄漏。