以编程方式设置自动布局约束

时间:2015-09-28 20:31:37

标签: ios swift autolayout nslayoutconstraint view-hierarchy

我无法弄清楚如何解决这个问题:我想创建一个匹配游戏,其中卡的大小取决于设备。

我以为我会创建一个contentView,我将其固定在rootView的顶部和底部,边距为20,并将其分配到其中心。然后我给它一个3/4的宽高比(3行和4列)。

let contentView = UIView()
// place contentView on the view
self.view.addSubview(contentView)
contentView.translatesAutoresizingMaskIntoConstraints = false

//add position constraints to thecontentView
let topMargin = NSLayoutConstraint(item: contentView, attribute: NSLayoutAttribute.Top, relatedBy: NSLayoutRelation.Equal, toItem: self.view, attribute: NSLayoutAttribute.Top, multiplier: 1, constant: 20)
let bottomMargin = NSLayoutConstraint(item: contentView, attribute: NSLayoutAttribute.Bottom, relatedBy: NSLayoutRelation.Equal, toItem: self.view, attribute: NSLayoutAttribute.Bottom, multiplier: 1, constant: -20)

let horzontalAllignment = NSLayoutConstraint(item: contentView, attribute: NSLayoutAttribute.CenterY, relatedBy: NSLayoutRelation.Equal, toItem: self.view, attribute: NSLayoutAttribute.CenterY, multiplier: 1, constant: 0)
let verticalAllignment = NSLayoutConstraint(item: contentView, attribute: NSLayoutAttribute.CenterX, relatedBy: NSLayoutRelation.Equal, toItem: self.view, attribute: NSLayoutAttribute.CenterX, multiplier: 1, constant: 0)

self.view.addConstraints([topMargin, bottomMargin, horzontalAllignment, verticalAllignment])

//  create an aspect ratio for the contentView
let aspect = NSLayoutConstraint(item: contentView, attribute: NSLayoutAttribute.Width, relatedBy: NSLayoutRelation.Equal, toItem: contentView, attribute: NSLayoutAttribute.Height, multiplier: 4/3, constant: 0)
contentView.addConstraint(aspect)

完美无缺。 (Whohoo!)然后我想创建一张具有四分之一contentView宽度和三分之一高度的卡片:

let thisCard = Card()
contentView.addSubview(thisCard)
thisCard.translatesAutoresizingMaskIntoConstraints = false

let hightConstraint = NSLayoutConstraint(item: thisCard, attribute: NSLayoutAttribute.Height, relatedBy: NSLayoutRelation.Equal, toItem: contentView, attribute: NSLayoutAttribute.Height, multiplier: 1/3, constant: 0)

let widthConstraint = NSLayoutConstraint(item: thisCard, attribute: NSLayoutAttribute.Width, relatedBy: NSLayoutRelation.Equal, toItem: contentView, attribute: NSLayoutAttribute.Width, multiplier: 1/4, constant: 0)

thisCard.addConstraints([hightConstraint, widthConstraint])

代码中断了,我收到了消息:

  

未为约束准备视图层次结构:   NSLayoutConstraint:0x78f1b290   Meeres_Memo_temp_caseinsensitive_renamery.Card:0x78f41820.height ==   UIView:0x78f49fc0.height当添加到视图时,约束的项目   必须是该视图的后代(或视图本身)。这会崩溃   如果需要在视图层次结构之前解析约束   组装

甚至可能,想要我想要吗?

更新

我刚发现错误。 我将heightConstraint和widthConstraint添加到thisCard中,但是它们需要添加到视图层次结构中较高的相关视图中,在本例中为contentView,如下所示:

contentView.addConstraints([hightConstraint, widthConstraint])

1 个答案:

答案 0 :(得分:0)

阅读错误消息。如果项目位于同一视图层次结构中,则只能添加约束。我认为您在将thisCard或contentView添加到视图层次结构之前尝试添加约束。你需要先做到这一点。

顺便说一句。 1/4并不是你的想法 - 它是一个很大的零点。 1/4使用整数除法。例如,使用1.0 / 4。

相关问题