带有自动布局的 uiscrollview 的动态内容未按预期工作
Posted
技术标签:
【中文标题】带有自动布局的 uiscrollview 的动态内容未按预期工作【英文标题】:Dynamic content to uiscrollview with autolayout not working as expected 【发布时间】:2019-02-04 18:01:07 【问题描述】:我正在尝试向滚动视图添加动态内容,如下所示
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
Cardview 是用自动布局定义的 xib
IB 中的视图结构如下 SuperView > ScrollView > ContentView > DynamicViews
ContentView 还包含一些静态内容,如按钮和标签。动态视图位于静态内容下方
输出屏幕如下所示,但未正确对齐
这是向滚动视图添加动态视图的正确方法吗?
【问题讨论】:
【参考方案1】:这是UIStackView
的理想案例
堆栈视图将处理实例化gameView
s 的垂直定位和宽度(假设您的 xib 加载设置正确)。
通过将堆栈视图的顶部、前导、尾随、底部和宽度约束到滚动视图,它还将定义“可滚动区域”(.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)
【讨论】:
我在动态数据上方有一些按钮和内容。在这种情况下 uistackview 是否完美运行? contentsize 会自动增加吗? 当然...您可以将堆栈视图的顶部限制在其他按钮和内容之下,或者也将这些元素放在堆栈视图中。以上是关于带有自动布局的 uiscrollview 的动态内容未按预期工作的主要内容,如果未能解决你的问题,请参考以下文章
使用自动布局向 UIScrollView 添加动态大小的视图(高度)
UITextView 使用自动布局动态扩展为滚动视图内的文本