[英]Change content size UIScrollView dynamically
我有一个滚动视图,当视图第一次加载时,大小是动态设置的,但是当我点击按钮时,我的元素的内部大小发生了变化,我需要改变滚动的内部大小,但它不会改变。 有人知道如何解决吗?
DispatchQueue.main.async {
var contentRect = CGRect()
for view in self.scrollView.subviews {
contentRect = contentRect.union(view.frame)
self.scrollView.contentSize = contentRect.size
}
}
如果你真的不想使用自动布局/约束,你可以在每次从滚动视图中添加(或删除)子视图时调用此函数,或者在更改子视图的大小后调用此函数(秒):
func updateContentSize() -> Void {
// this will get the right-edge of the right-most subview
let width = scrollView.subviews.map {$0.frame.maxX}.max() ?? 0.0
// this will get the bottom-edge of the bottom-most subview
let height = scrollView.subviews.map {$0.frame.maxY}.max() ?? 0.0
// set the contentSize
scrollView.contentSize = CGSize(width: width, height: height)
}
此解决方案适用于自动布局/约束。 您需要一个引用约束来操纵滚动视图的内部容器视图的高度。
private var _constraintInnerContainerScroll:NSLayoutConstraint?
需要设置内部容器view的初始高度,假设700.0
private let _containerViewHeightFixed : CGFloat = 700.0
那么你需要保存参考
_constraintInnerContainerScroll = _containerView.heightAnchor.constraint(equalToConstant: _containerViewHeightFixed)
_constraintInnerContainerScroll?.isActive = true
您的初始视图已设置并准备就绪,现在假设您再添加 2 个高度为 100.0 的子视图,现在您的新内部容器视图高度应为 700.0+200.0 = 900.0
if let const1 = _constraintInnerContainerScroll{
const1.constant = _containerViewHeightFixed + 200.0
UIView.animate(withDuration: 0.5) {
self?._containerView.layoutIfNeeded()
}else{
print("constraint reference not saved")
}
让我知道这是否适合您,或者是否可以改进。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.