【问题标题】:Creating and assigning CGRect to a UIView within a for loop在 for 循环中创建 CGRect 并将其分配给 UIView
【发布时间】:2016-09-15 01:30:46
【问题描述】:

我正在循环 [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()))

【问题讨论】:

  • 请说明您是如何创建questionViews 数组的
  • @SamM: 更新:)

标签: ios swift for-loop uiview cgrect


【解决方案1】:

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

替换这个:

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

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

【讨论】:

    猜你喜欢
    • 2017-11-04
    • 1970-01-01
    • 1970-01-01
    • 2018-05-16
    • 1970-01-01
    • 2019-01-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多