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

时间:2016-09-15 01:30:46

标签: ios swift for-loop uiview cgrect

我循环浏览[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数组在init中设置,只有空CGRects开头:

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

1 个答案:

答案 0 :(得分:3)

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

替换这个:

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

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