当用户按下ViewController1中的按钮时,我希望它在ViewController2中调用一个函数。我认为我唯一缺少的是将ViewController2分配为其自己的委托,但是如何将self声明为委托?
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)
}
}
视图控制器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时,应为其分配委托。
例如:
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 - 我如何将自己设置为代表?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/45807218/