我要以相同的高度,宽度和相同的x值定位3个uibtton,唯一要更改的是我希望每个uibutton添加40 positivie来分隔它。我认为有某种方法可以通过循环执行此操作,而不是像下面那样手动执行此操作。我希望(equalTo:view.centerYAnchor,constant:0)每次被yP加40替换。

   var yP = 0


    undoButton.trailingAnchor.constraint(equalTo: view.centerXAnchor, constant :25),
       undoButton.topAnchor.constraint(equalTo: view.centerYAnchor, constant : 0),
       undoButton.widthAnchor.constraint(equalToConstant: CGFloat(widthBox)),
       undoButton.heightAnchor.constraint(equalToConstant: 20),

       clearButton.trailingAnchor.constraint(equalTo: view.centerXAnchor, constant :25),
       clearButton.topAnchor.constraint(equalTo: view.centerYAnchor, constant : 40),
       clearButton.widthAnchor.constraint(equalToConstant: CGFloat(widthBox)),
       clearButton.heightAnchor.constraint(equalToConstant: 20),

       color.trailingAnchor.constraint(equalTo: view.centerXAnchor, constant :25),
       color.topAnchor.constraint(equalTo: view.centerYAnchor, constant : 80),
       color.widthAnchor.constraint(equalToConstant: CGFloat(widthBox)),
       color.heightAnchor.constraint(equalToConstant: 20),

最佳答案

尝试这个。

func setConstraints() {
    var yPosition: CGFloat = 0

    [undoButton, clearButton, color].forEach { button in
        NSLayoutConstraint.activate([
            button.trailingAnchor.constraint(equalTo: view.centerXAnchor, constant :25),
            button.topAnchor.constraint(equalTo: view.centerYAnchor, constant : yPosition),
            button.widthAnchor.constraint(equalToConstant: CGFloat(widthBox)),
            button.heightAnchor.constraint(equalToConstant: 20)
        ])
        yPosition += 40
    }
}

10-04 17:49