如何将自己设为代表?

时间:2017-08-22 00:23:32

标签: ios swift delegates

当用户按下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!")
    }

}

1 个答案:

答案 0 :(得分:4)

实例化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)