簡體   English   中英

如何將自我設置為代表?

[英]How do I set self as delegate?

當用戶在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)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM