在 for 循环中创建 CGRect 并将其分配给 UIView

Creating and assigning CGRect to a UIView within a for loop

我正在循环 [UIView],设置它们的框架,然后将它们作为子视图添加到 UIScrollView。在代码中,我分配了一个随机的背景颜色,这样我就可以区分视图以进行测试:

for i in 0...questionViews.count - 1 {
    let hue: CGFloat = CGFloat(arc4random() % 256) / 256
    let saturation: CGFloat = CGFloat(arc4random() % 128) / 256 + 0.5
    let brightness: CGFloat = CGFloat(arc4random() % 128) / 256 + 0.5

    questionViews[i].backgroundColor = UIColor(hue: hue, saturation: saturation, brightness: brightness, alpha: 1)

    questionViews[i].frame = CGRect(x: screen.width * CGFloat(i), y: 0, width: screen.width, height: screen.height)
    questionsScrollView!.addSubview(questionViews[i])
}

但是,如果我遍历这些并打印它们:

for i in 0...questionViews.count - 1 {
    print(questionViews[i].frame)
}

结果将是:

(3000.0, 0.0, 375.0, 667.0)
(3000.0, 0.0, 375.0, 667.0)
(3000.0, 0.0, 375.0, 667.0)
(3000.0, 0.0, 375.0, 667.0)
(3000.0, 0.0, 375.0, 667.0)
(3000.0, 0.0, 375.0, 667.0)
(3000.0, 0.0, 375.0, 667.0)
(3000.0, 0.0, 375.0, 667.0)
(3000.0, 0.0, 375.0, 667.0)

为什么每个 CGRect 都有来自 for 循环的最终值 x?

编辑:

questionViews 数组在初始化中设置为空 CGRects 开头:

questionViews = [UIView](count: numberOfQuestions, repeatedValue: UIView(frame: CGRect()))

当创建一个包含引用类型重复值的数组时,它只创建一个项目并将所有索引指向该项目。所以在你的 for 循环中,你一遍又一遍地敏锐地设置那个 UIView 的所有索引的框架。

替换为:

questionViews = [UIView](count: numberOfQuestions, repeatedValue: UIView(frame: CGRect()))

var questionViews = [UIView]()
for _ in 0..<numberOfQuestions {
    questionViews.append(UIView(frame: CGRect()))
}