创建CGRect并将其分配给for循环中的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
数组在init中设置,只有空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()))
}
链接地址: http://www.djcxy.com/p/82007.html
上一篇: Creating and assigning CGRect to a UIView within a for loop