简体   繁体   English

无法设置Swift中UIScrollView的子视图UIView的backgroundColor

[英]Cannot set backgroundColor of UIView which is a subview of UIScrollView in Swift

I try to add some UIView objects as subviews to a UIScrollView and give them random color. 我尝试将一些UIView对象作为子视图添加到UIScrollView并为其赋予随机颜色。 But these UIView objects' backgroundColor are white. 但是这些UIView对象的backgroundColor是白色的。 Why can't I set their backgroundColor? 为什么不能设置他们的backgroundColor?

I run this project on iOS 10.1, Swift 3.0.1 and SnapKit 3.0.2. 我在iOS 10.1,Swift 3.0.1和SnapKit 3.0.2上运行此项目。 Here is code in viewDidLoad : 这是viewDidLoad代码:

let scrollView = UIScrollView.init()
scrollView.isPagingEnabled = true

self.view.addSubview(scrollView)
scrollView.snp.makeConstraints { (make) in
    make.left.right.top.bottom.equalTo(self.view)
}

var lastView: UIView? = nil
for i in 0 ..< 5 {
    let colorView = UIView.init()
    let red = CGFloat(arc4random() % 256) / 255.0
    let blue = CGFloat(arc4random() % 256) / 255.0
    let green = CGFloat(arc4random() % 256) / 255.0
    colorView.backgroundColor = UIColor.init(red: red, green: green, blue: blue, alpha: 1.0)
    scrollView.addSubview(colorView)

    colorView.snp.makeConstraints({ (make) in
        make.top.bottom.equalTo(scrollView)
        make.width.equalTo(scrollView)

        if i == 0 {
            make.left.equalTo(scrollView)
        }
        else {
            make.left.equalTo((lastView?.snp.right)!)
        }

        if i == 4 {
            make.right.equalTo(scrollView)
        }
    })
    lastView = colorView
}

I think the problem is that the backgroundColor of scrollView will cover on the `colorView'. 我认为问题是, backgroundColorscrollView将覆盖在'colorView”。

您是否可能需要添加make.height.equalTo(scrollView) ...我没有看到高度限制...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM