this means war this means war - 1 month ago 8
iOS Question

How do I set self as delegate?

When the user pushes the button in ViewController1, I want it to call a function in ViewController2. I think the only thing I'm missing is assigning ViewController2 as its own delegate, but how do you declare self as 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!")
}

}

Answer Source

When you instantiate VC2, you should assign delegate to it. For example:

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)