鍍金池/ 問答/C  iOS/ 在特定條件下UIButton 無法響應(yīng)事件!

在特定條件下UIButton 無法響應(yīng)事件!

在項(xiàng)目的某個(gè)需求中嘗試將一個(gè)UIController.view加入到另一個(gè)OtherController.view中或者是一個(gè)UIView鐘當(dāng)并不設(shè)置UIController為OtherController的childController,那么就無法響應(yīng)UIController中UIButton的事件,這是什么原因?另外有什么辦法使其可以響應(yīng)Button事件。

回答
編輯回答
怣人

因?yàn)槟愕?controller 釋放了啊,沒有人持有

2017年9月16日 10:43
編輯回答
安于心

已知道原因,突然想到會不會因?yàn)槭巧芷诘脑?,在某個(gè)view方法內(nèi)add UIViewController.view后controller的生命周期就結(jié)束了,所以嘗試將UIViewController作為屬性持有它,就可以響應(yīng)Button的事件了。

class ViewController: UIViewController {

//    let controller = CustomViewController()
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        let contentView = UIView(frame: CGRect(x: 30, y: 100, width: 300, height: 300))
        contentView.backgroundColor = UIColor.red
        
        let controller = CustomViewController()    // 注釋掉這行,改成上面的屬性就可以了
        controller.view.backgroundColor = UIColor.yellow
//        self.addChildViewController(controller)
        controller.view.frame = contentView.bounds;
        contentView.addSubview(controller.view)
        
        self.view .addSubview(contentView)
        
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
}
2017年3月5日 09:39