2015-09-28 141 views
2

我无法弄清楚如何解决这个问题:我想创建一个匹配游戏,其中卡的大小取决于设备。以编程方式设置自动布局约束

我以为我会创建一个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)然后我想创建一个具有内容查看宽度的四分之一和HIGHT的第三一张牌:

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.addConstraints([hightConstraint, widthConstraint]) 
+0

看看这个库,它可能以编程方式帮助你约束。 https://github.com/PureLayout/PureLayout –

回答

0

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

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

+0

你能澄清一下吗?我将contenView添加为rootview的子视图,并将该卡添加为contentView的子视图(在上面的代码中)。还有什么我需要做的吗? – Myriam

相关问题