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



我正在通过[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()))
}

最新更新