2017-06-21 51 views
2

好吧,我剛剛遇到了奇怪的事情。我有我的應用程序控制器依賴注入視圖(標題)到視圖控制器。該視圖控制器以模態方式呈現另一個視圖控制器,並且依賴注入它自己的頭以供呈現視圖控制器使用。但是,當它從第一個控制器提交標題消失。爲什麼在呈現視圖控制器後UIView從圖層中刪除?

屬性仍然設置,但它已從視圖層次結構中刪除。

class ViewController: UIViewController { 
    override func viewDidLoad() { 
     super.viewDidLoad() 

     self.view.backgroundColor = .white 

     let button = UIButton(frame: CGRect(x: 0, y: 20, width: 100, height: 50)) 
     button.setTitle("Click Me!", for: .normal) 
     button.addTarget(self, action: #selector(self.segue), for: .touchUpInside) 
     button.backgroundColor = .black 
     button.setTitleColor(.lightGray, for: .normal) 

     self.view.addSubview(button) 
    } 

    func segue() { 
     let view = UIView(frame: CGRect(x: 0, y: 0, width: 200, height: 200)) 
     view.backgroundColor = .lightGray 

     let firstVC = FirstViewController() 
     firstVC.sharedView = view 

     present(firstVC, animated: false) 
    } 
} 

class FirstViewController: UIViewController { 
    var sharedView: UIView! 

    override func viewDidLoad() { 
     super.viewDidLoad() 
     self.view.backgroundColor = .white 

     self.view.addSubview(self.sharedView) 

     let button = UIButton(frame: CGRect(x: 0, y: 200, width: 100, height: 50)) 
     button.setTitle("Click Me!", for: .normal) 
     button.addTarget(self, action: #selector(self.segue), for: .touchUpInside) 
     button.backgroundColor = .black 
     button.setTitleColor(.lightGray, for: .normal) 

     self.view.addSubview(button) 
    } 

    func segue() { 
     let secondVC = SecondViewController() 
     secondVC.sharedView = self.sharedView 

     present(secondVC, animated: true) 
    } 
} 

class SecondViewController: UIViewController { 
    var sharedView: UIView! 

    override func viewDidLoad() { 
     super.viewDidLoad() 
     self.view.backgroundColor = .white 

     self.view.addSubview(self.sharedView) 

     let button = UIButton(frame: CGRect(x: 0, y: 200, width: 100, height: 50)) 
     button.setTitle("Click Me!", for: .normal) 
     button.addTarget(self, action: #selector(self.segue), for: .touchUpInside) 
     button.backgroundColor = .black 
     button.setTitleColor(.lightGray, for: .normal) 

     self.view.addSubview(button) 
    } 

    func segue() { 
     self.dismiss(animated: true) 
    } 
} 

有人能解釋什麼是怎麼回事:

我在新鮮singleview項目重現這個問題?爲什麼sharedView從FirstViewController中消失?

+2

在'addSubview()'的文檔中:'Views只能有一個超級視圖。如果視圖已經有一個超級視圖,並且該視圖不是接收者,那麼在使接收者成爲新的超級視圖之前,此方法將刪除先前的超級視圖。「我認爲這是問題所在。你可能想要這個:https://stackoverflow.com/questions/4425939/can-uiview-be-copied – Larme

+0

啊,這是有道理的。任何建議,使其正常工作? –

+0

我編輯了我以前的評論與可能的解決方案。但是我會使用一種方法來創建該頭部視圖並進行所有自定義並調用它。 – Larme

回答

1

截至-addSubview(_:)商務部:

視圖只能有一個上海華。如果視圖已經有一個超級視圖,並且該視圖不是接收者,則在使接收者成爲新的超級視圖之前,此方法將刪除以前的超級視圖。

這應該解釋你的問題。

我建議您改爲創建一個方法,根據您的自定義風格生成headerView(每次都有一個新的)。

如果您真的想「複製」該視圖,可以查看that answer。由於UIViewNSCopying標準,他們的訣竅是「存檔/編碼」它,因爲它是NSCoding兼容,複製歸檔和「取消存檔/解碼」它的副本。

相關問題