create a loop to space 2 different objects on a uiviewcontroller

不打扰是莪最后的温柔 提交于 2020-01-06 05:25:29

问题


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
}

}


回答1:


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.



来源:https://stackoverflow.com/questions/58741091/create-a-loop-to-space-2-different-objects-on-a-uiviewcontroller

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!