簡體   English   中英

使用自動布局確定UIView的寬度-SWIFT

[英]Determining width of a UIView using autolayout - SWIFT

好了,因此在界面構建器( Main.storyboard )中,我在UIScrollView嵌入了containerView:UIView containerView我想創建其他UIView來容納內容塊,例如標題,正文等。之所以這樣做,是為了使內容可以垂直滾動,而不能水平滾動。

我的目標是使用自動布局來創建這些不同的UIView 到目前為止,containerView會根據所使用設備的屏幕尺寸自動調整其寬度,以防止水平滾動。 它使用我為寬度約束創建的IBOutlet進行此操作。 當前看起來像這樣:

@IBOutlet var containerView: UIView!
@IBOutlet var containerViewWidthConstraint: NSLayoutConstraint!

override func viewDidLoad() {
    super.viewDidLoad()

    //Prevents horizontal scrolling
    containerViewWidthConstraint.constant = self.view.frame.size.width

    createHeader()
}

然后,我創建了一個名為createheader{}的函數,該函數將headerView:UIViewcontainerView的頂部,並從containerView任一邊緣固定8個點:

func createHeader() {
    //Create header
    let headerView = UIView()
    headerView.backgroundColor = UIColor.blueColor()
    self.containerView.addSubview(headerView)

    //Create header constraints
    let leftMargin = NSLayoutConstraint(item: headerView, attribute: .Leading, relatedBy: .Equal, toItem: containerView, attribute: .Leading, multiplier: 1.0, constant: 8)
    let rightMargin = NSLayoutConstraint(item: containerView, attribute: .Trailing, relatedBy: .Equal, toItem: headerView, attribute: .Trailing, multiplier: 1.0, constant: 8)
    let topMargin = NSLayoutConstraint(item: headerView, attribute: .Top, relatedBy: .Equal, toItem: containerView, attribute: .Top, multiplier: 1.0, constant: 70)
    let heightConstraint = NSLayoutConstraint(item: headerView, attribute: .Height, relatedBy: .Equal, toItem: nil, attribute: NSLayoutAttribute.NotAnAttribute, multiplier: 1.0, constant: 160)

    //Activate header constraints
    headerView.setTranslatesAutoresizingMaskIntoConstraints(false)
    NSLayoutConstraint.activateConstraints([leftMargin,rightMargin,topMargin,heightConstraint])

    println(headerView.frame.size.width)
}

現在,由於headerView內部內容的大小將取決於所使用設備的屏幕大小,因此我希望能夠創建根據headerView本身寬度的大小來確定內容寬度大小的headerView 但是,每次我嘗試使用以下方法獲取headerView的寬度:

println(headerView.frame.size.width)

它返回零值,顯然不是這種情況,因為它仍根據上述約束創建藍底headerView

為什么SWIFT無法識別headerView具有寬度? 以及如何獲取headerView的寬度?

安裝約束后,如果要立即更新框架,則需要調用layoutIfNeeded

func createHeader() {
    //Create header
    let headerView = UIView()
    headerView.backgroundColor = UIColor.blueColor()
    self.containerView.addSubview(headerView)

    ...

    //Activate header constraints
    headerView.setTranslatesAutoresizingMaskIntoConstraints(false)
    NSLayoutConstraint.activateConstraints([leftMargin,rightMargin,topMargin,heightConstraint])

    self.containerView.layoutIfNeeded() // Updates the frames
    println(headerView.frame.size.width) // Will output the correct width
}

請注意,這將在UI循環的下一次迭代中自動發生,但是,當您希望立即查看效果時,這對您沒有幫助。

暫無
暫無

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

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