2017-05-24 39 views
0

我想創建一個基於視圖大小的容器視圖。代碼自身說明,但不起作用。我試過使用覆蓋viewWillAppear無濟於事。NSLayoutConstraints不參考視圖

進口的UIKit

class ViewController: UICollectionViewController, UICollectionViewDelegateFlowLayout, UITextFieldDelegate { 

let searchBarContainer: UIView = { 
    let sBarContainer = UIView() 
    sBarContainer.backgroundColor = UIColor.gray 
    return sBarContainer 
}() 



override func viewDidLoad() { 
    super.viewDidLoad() 
    navigationItem.title = "Search Bar" 
    collectionView?.backgroundColor = UIColor.white 

    view.addSubview(searchBarContainer) 

    NSLayoutConstraint(item: searchBarContainer, attribute: .width, relatedBy: .equal, toItem: view, attribute: .width, multiplier: 1, constant: 0).isActive = true 

    NSLayoutConstraint(item: searchBarContainer, attribute: .height, relatedBy: .equal, toItem: view, attribute: .height, multiplier: 1, constant: 0).isActive = true 

    NSLayoutConstraint(item: searchBarContainer, attribute: .bottom, relatedBy: .equal, toItem: view, attribute: .bottom, multiplier: 1, constant: 0).isActive = true 

    } 


} 

有什麼建議?謝謝

+1

您沒有任何設置子視圖的x位置 – dan

+3

您還需要將'translatesAutoresizingMaskIntoConstraints'設置爲false – dan

回答

1

像這樣創建NSLayoutConstraints只會返回約束。您需要將它們添加到父視圖中,或者如果您是iOS 8或更高版本,您可以使用更優質的佈局錨。

因此,舉例來說:

NSLayoutConstraint(item: searchBarContainer, attribute: .width, relatedBy: .equal, toItem: view, attribute: .width, multiplier: 1, constant: 0).isActive = true

成爲

label.widthAnchor.constraint(equalTo: view.widthAnchor).isActive = true

編輯:要說清楚,錨路線意味着你不必應付手動添加創建它們之後。