Swift 使用 AutoLayout 更改按钮位置

Swift Change button position with AutoLayout

我以这种方式以编程方式创建了按钮

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 放置行和列?

你走对了!问题是您的计算在 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。如果您希望这些按钮位于不同的位置,您需要 更大的差异!

(显然,您还应该将 line 声明或强制转换为 CGFloat。)