songlebao songlebao - 1 month ago 16
Swift Question

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'.

Answer

Do you potentially need to add make.height.equalTo(scrollView) ... I don't see a height constraint...

Comments