当用户按下 ViewController1 中的按钮时,我希望它调用 ViewController2 中的函数。我认为我唯一缺少的就是将 ViewController2 指定为其自己的委托(delegate),但是如何将 self 声明为委托(delegate)?
ViewController1
protocol VC1Delegate {
func pushThisButton(_ sender: UIButton)
}
class ViewController1: UIViewController {
var delegate: VC1Delegate!
var theButton = UIButton()
override func viewDidLoad() {
super.viewDidLoad()
buildButton()
}
func pushButton(_ sender: UIButton) {
delegate.pushThisButton(theButton)
}
func buildButton() {
theButton = UIButton(frame: CGRect(x: 100, y: 100, width: 200, height: 50))
theButton.backgroundColor = UIColor.black
theButton.addTarget(self, action: #selector(pushButton), for: .touchUpInside)
self.view.addSubview(theButton)
}
}
View Controller 2
class ViewController2: UIViewController, VC1Delegate {
// I'm guessing somewhere here I need to declare myself as the delegate?
override func viewDidLoad() {
super.viewDidLoad()
}
func pushThisButton(_ sender: UIButton) {
print("Damnit, Jack! Push the damn button!")
}
}
最佳答案
当你实例化VC2时,你应该给它分配委托(delegate)。
例如:
protocol VC1Delegate: class {
func pushThisButton(_ sender: UIButton)
}
class ViewController1: UIViewController {
weak var delegate: VC1Delegate?
...
let vc2 = ViewController2()
self.delegate = vc2 // we are in the VC1 context
self.navigationController.pushViewController(vc2, animated: true)
关于ios - 如何将自己设置为委托(delegate)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45807218/