我正尝试将动态内容添加到滚动视图中,如下所示
for i in 0 ..< 4 {
let gameView = Card.instantiate()
gameView.frame.origin.y = gameView.frame.size.height * CGFloat(i)
contentView.addSubview(gameView)
gameView.centerXAnchor.constraint(equalTo: contentView.centerXAnchor).isActive = true
let widthConstraint = NSLayoutConstraint(item: gameView, attribute: .width, relatedBy: .equal,toItem: contentView, attribute: .width, multiplier: 0.8,constant : 0.0)
contentView.addConstraint(widthConstraint)
let heightConstraint = NSLayoutConstraint(item: gameView, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .height, multiplier: 1.0, constant: 100)
gameView.addConstraint(heightConstraint)
contentView.frame.size.height = contentView.frame.size.height + gameView.frame.size.height
scrollView.contentSize.height = scrollView.contentSize.height + gameView.frame.size.height
}
IB中的视图结构如下SuperView> ScrollView> ContentView> DynamicViews
ContentView还包含一些静态内容,例如按钮和标签。动态视图位于该静态内容下方
这是向滚动视图添加动态视图的正确方法吗?
答案 0 :(得分:0)
这是UIStackView
堆栈视图将处理实例化的gameView
的垂直位置和宽度(假设您正确设置了xib加载)。
通过将堆栈视图的顶部,顶部,底部,底部和底部宽度限制到scrollView,它还将定义“可滚动区域”(.contentSize
)。
所有操作均通过自动布局完成:
let sv = UIStackView()
sv.axis = .vertical
sv.alignment = .fill
sv.distribution = .fill
sv.spacing = 0 // change to add vertical spacing if desired
sv.translatesAutoresizingMaskIntoConstraints = false
scrollView.addSubview(sv)
NSLayoutConstraint.activate([
sv.topAnchor.constraint(equalTo: scrollView.topAnchor),
sv.bottomAnchor.constraint(equalTo: scrollView.bottomAnchor),
sv.leadingAnchor.constraint(equalTo: scrollView.leadingAnchor),
sv.trailingAnchor.constraint(equalTo: scrollView.trailingAnchor),
sv.widthAnchor.constraint(equalTo: scrollView.widthAnchor, multiplier: 1.0),
])
for _ in 0 ..< 4 {
let gameView = Card.instantiate()
gameView.translatesAutoresizingMaskIntoConstraints = false
gameView.heightAnchor.constraint(equalToConstant: 100.0).isActive = true
sv.addArrangedSubview(gameView)
}