loopsfor-loopforeachnslayoutconstraintcgfloat

create a loop to space 2 different objects on a uiviewcontroller


My code below does exactly what I am looking for the problem is it just does this in a uibtton. I would like to do the same thing with 2 uitextfields and 2 uilabels. So textfield to uilabel to textfield to uilabel. I assume you would just have to change "button in" but I dont know what to change it with. I want the objects spaced 40 between each other just like below.

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
}

}


Solution

  • Just put your text fields and labels in the desired order in an array, and replace the [undoButton, clearButton, color] part with it. You technically don't need to change the button in part, as it is just a variable name.

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

    Note that UIStackView might make your life much easier. I suggest you have a look at how to use that.