【发布时间】:2017-07-31 20:51:17
【问题描述】:
我能够初始化我的滚动视图并使用背景颜色设置它的 contentSize...完成后一切正常,但是当我使用以下代码将子视图添加到滚动视图时,我无法看到这些视图...请帮助?
func setupViews(_ views: [NewView]) {
var multiplier: CGFloat = 0.0
let width = frame.size.width
let height = frame.size.height
for view in views {
let newView = NewView()
addSubview(newView)
newView.frame = CGRect(x: width * multiplier, y: 0, width: width, height: height)
newView.backgroundColor = .random()
newView.centerYAnchor.constraint(equalTo: centerYAnchor).isActive = true
newView.centerXAnchor.constraint(equalTo: centerXAnchor, constant: width * multiplier).isActive = true
multiplier += 1
}
contentSize = CGSize(width: width * multiplier, height: height)
}
我在 NewView 类中有一个 commonInit() 函数,它在必需的 init 和 override init 中都被调用,可能会有所帮助,所以在这里
private func commonInit() {
translatesAutoresizingMaskIntoConstraints = false
backgroundColor = UIColor.white
let labels = [nameLabel, brandLabel, priceLabel]
var multiplier: CGFloat = 0.0
for label in labels {
addSubview(label)
label.translatesAutoresizingMaskIntoConstraints = false
label.centerYAnchor.constraint(equalTo: centerYAnchor, constant: 10.0 * multiplier).isActive = true
label.centerXAnchor.constraint(equalTo: centerXAnchor, constant: 0.0).isActive = true
multiplier += 1.0
}
}
【问题讨论】:
-
如果您要使用自动布局约束设置视图的位置,那么您还必须使用它们来设置大小。