如何使用框架在Swift上的循环中设置x位置 [英] How to use frame to set x position in loop on Swift
本文介绍了如何使用框架在Swift上的循环中设置x位置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个数组,计数在1到3之间变化. 我想在屏幕中间以一定距离构图 标签的宽度也是固定的
I have an array that count is between 1 to 3 varies. I want to frame them in the middle of the screen with a certain distance Also the width of the labels is fixed
let array = ["some1", "some2", "some3"]
func setLabel(){
var i = -1
for text in array{
i += 1
let label = UILabel()
label.fram = CGRect(x: screenWidth/2 - (CGFloat(i)*50) + 25, y: 100, width: 50 , height: 20)
label.text = text
addSubview(label)
}
}
推荐答案
您可以按照 @matt 的建议使用stackview .如果您不想使用stackview,可以像这样通过数组计数和标签索引来计算x位置
You can use stackview as suggested by @matt. If you don't want to use stackview you can calculate the x position by array count and label index like this
let array = ["some1", "some2", "some3"]
func setLabel(){
var i:CGFloat = 0
for text in array{
i += 1
let label = UILabel()
label.backgroundColor = .red
label.frame = CGRect(x: (view.bounds.width/CGFloat(array.count+1))*i-25, y: 100, width: 50 , height: 20)
label.text = text
view.addSubview(label)
}
}
这篇关于如何使用框架在Swift上的循环中设置x位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文