2017-08-22 5 views
1

ユーザーがViewController1のボタンを押すと、ViewController2の関数を呼び出すようにします。私は唯一の欠点は、独自のデリゲートとしてViewController2を割り当てることだと思いますが、デリゲートとしてどのように自分自身を宣言しますか?デリゲートとして自分を設定するにはどうすればよいですか?

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!") 
    } 

} 
+0

は、あなたのコードの一部では、あなたが、これは一般的にViewController2プレゼンテーションで行われ、あなたのViewController1のデリゲートプロパティをASSING必要、 'viewController1.delegate = viewController2'のようなものもあります。代理人のためには、varの後にweakを使う必要があります。そうでなければ、サイクルが保たれ、アプリケーションにメモリの問題が発生します。 –

+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) 
+0

私は実際に.delegateのプロパティを持っているvc1だと思います。 –

+0

は実際には 'self.delegate = vc2'でなければなりません//私たちはVC1のコンテキストにあります –

+0

はい、確かです。一定。 – helloworlt

関連する問題