我以这种方式以编程方式创建了按钮
func CreateButtonWithIndex(index:Int) {
let widthButton = 120
let heightButton = 80
let line = (index / 3)
let column = index % 3
let newButton = UIButton.buttonWithType(UIButtonType.System) as UIButton
newButton.frame = CGRect(x:line*widthButton+95, y:column*heightButton+15, width:widthButton, height:heightButton)
self.view.addSubview(newButton)
}
现在尝试以这种方式为此按钮放置NSLayoutConstraint
func CreateButtonWithIndex(index:Int) {
let widthButton = 120
let heightButton = 80
let line = (index / 3)
let column = index % 3
let newButton = UIButton.buttonWithType(UIButtonType.System) as UIButton
newButton.setTranslatesAutoresizingMaskIntoConstraints(false)
self.view.addSubview(newButton)
let constraint1 = NSLayoutConstraint(item: newButton, attribute: .CenterX, relatedBy: .Equal, toItem: view, attribute: .CenterX, multiplier: 1, constant: 1)
let constraint2 = NSLayoutConstraint(item: newButton, attribute: .CenterY, relatedBy: .Equal, toItem: view, attribute: .CenterY, multiplier: 1, constant: 10)
view.addConstraints([constraint1,constraint2])
}
但显然我只是在同一个位置创建了各种按钮。 我试过例如
let constraint1 = NSLayoutConstraint(item: newButton, attribute: .CenterX, relatedBy: .Equal, toItem: view, attribute: .CenterX, multiplier: 1, constant: line)
但不要去!!!
如何使用NSLayoutConstraint放置行和列?
答案 0 :(得分:0)
你走在正确的轨道上!问题是你的计算没有在x位置给出足够大的差异。你在说:
let constraint1 = NSLayoutConstraint(
item: newButton, attribute: .CenterX, relatedBy: .Equal,
toItem: view, attribute: .CenterX, multiplier: 1, constant: line)
但是line
是什么?
let line = (index / 3)
好吧,如果index
为0,则为1,然后为2,line
每次都为0。如果您希望这些按钮位于不同的位置,则需要多更大的差异!
(显然,您也应该向CGFloat声明或投射line
。)