简体   繁体   中英

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. But these UIView objects' backgroundColor are white. Why can't I set their backgroundColor?

I run this project on iOS 10.1, Swift 3.0.1 and SnapKit 3.0.2. Here is code in 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'.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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