在 Swift 中循环创建 UIImageView 和标签

Loop to create UIImageView and Labels in Swift

您好!


我有一个作业,我需要使用一个循环,在屏幕上生成四个UIImageViews和16个标签,如图所示(不需要生成额外的元素)。


所以,总的来说,我想我明白怎么做了,但我有一些问题: 我需要使用 for i in 0 ... 3 循环,其中我说 var image = UIImageView ()?


var currentY: CGFloat = 0
    let width: CGFloat = 375
    let height: CGFloat = 100
    var images = [UIImage] ()


while i <4 {

if i = 1 {



var currentY: CGFloat + 10
    let width: CGFloat = 375
    let height: CGFloat = 100
    var images = [UIImage] ()
i + = 1

}

if i = 2 {

var currentY: CGFloat + 10
    let width: CGFloat = 375
    let height: CGFloat = 100
    var images = [UIImage] ()
}


像那样?这不是我所看到的代码,更多的是将我的想法收集到至少某些东西中的伪代码)
要在屏幕上放置元素,我需要给它们在屏幕上的坐标,我是否应该将这些坐标放入变量中并通过一些步骤更改它们?比如每次进入循环时将所有坐标加+10?
我需要为每个数字编写自己的代码吗?比如 if = 1 then if equal to 2 then ...


谢谢!

你可以通过两个for循环来做到这一点。第一个 FOR 循环用于每一行,第二个 FOR 循环用于设置每一行图像视图。

var y: CGFloat = 0.0
var height: CGFloat = 200.0
var width: CGFloat = 150.0

for _ in 0...2 {
    var x: CGFloat = 0.0
    for _ in 0...2 {
       let imgView = UIImageView()
       imgView.frame = CGRect(x: x, y: y, width: width, height: height)
       self.view.addSubView(imgView)
       x = x + width
    }
    y = y + height
}

这就是完整的答案:)

 func loop() {
    var y: CGFloat = 0.0
    let height: CGFloat = 200
    let width: CGFloat = 180
    var x:CGFloat = 0.0
    let colorsss:[UIColor] = [.purple,.blue,.brown,.cyan]
    var image = UIImageView()
    for i in 0...3 {
        image = UIImageView(frame: CGRect(x: x, y: y, width: width, height: height))
        image.backgroundColor = colorsss[i]
        view.subviews(image)
        var label = UILabel()
        let colors:[UIColor] = [.red,.yellow,.orange,.black]
        for i in 0...3 {
            if i == 3 {
                label = UILabel(frame: CGRect(x: width - width / 4, y: 180, width: width / 4 - CGFloat(i), height: 20))
                label.backgroundColor = colors[i]
                image.subviews(label)
            } else {
                label = UILabel(frame: CGRect(x: 0, y: 120 + (i * 20), width: Int(width / 4 - CGFloat(i)), height: 20))
                label.backgroundColor = colors[i]
                image.subviews(label)
            }
            
        }
        if i == 0 {
            x = x + width
        } else if i == 1 {
            y = y + height
            x = 0
        } else  {
            x = x + width
            y = height
        }
    }
}