创建一个循环以在uiviewcontroller上间隔2个不同的对象 [英] create a loop to space 2 different objects on a uiviewcontroller
问题描述
下面的代码正是我在寻找问题的方法,它只是在uibtton中执行此操作.我想对2个uitextfields和2个uilabels做同样的事情.因此,将textfield转换为uilabel,将textfield转换为uilabel.我认为您只需要更改按钮输入"即可,但是我不知道该如何更改.我希望对象之间的间隔为40,如下所示.
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
}
}
推荐答案
只需将您的文本字段和标签按所需顺序放入数组中,并用它替换[undoButton, clearButton, color]
部分.从技术上讲,您不需要更改button in
部分,因为它只是一个变量名.
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
}
请注意, UIStackView
可能会使您的生活更加轻松.我建议您看看如何使用它.
Note that UIStackView
might make your life much easier. I suggest you have a look at how to use that.
这篇关于创建一个循环以在uiviewcontroller上间隔2个不同的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!