【发布时间】:2021-02-14 06:42:36
【问题描述】:
我有以下代码来设置 UIScrollView 的子视图。我首先创建了一个名为 MyScrollView 的 UIScrollView 子类。然后我添加一个名为 contentView 的视图作为子视图。我将所有其他视图添加到滚动视图作为此 contentView 的子视图。问题是在使用自动布局约束设置以下代码后,scrollView 不滚动。
public class MyScrollView:UIScrollView {
private var contentView:UIView!
override init(frame: CGRect) {
super.init(frame: frame)
self.translatesAutoresizingMaskIntoConstraints = false
self.isScrollEnabled = true
self.isDirectionalLockEnabled = true
self.showsHorizontalScrollIndicator = true
self.showsVerticalScrollIndicator = false
self.decelerationRate = .normal
self.delaysContentTouches = false
self.bouncesZoom = true
setupSubviews()
}
private func setupSubviews() {
contentView = UIView()
contentView.backgroundColor = UIColor.clear
contentView.translatesAutoresizingMaskIntoConstraints = false
contentView.isUserInteractionEnabled = true
self.addSubview(contentView)
contentView.leadingAnchor.constraint(equalTo: self.leadingAnchor).isActive = true
contentView.trailingAnchor.constraint(equalTo: self.trailingAnchor).isActive = true
contentView.topAnchor.constraint(equalTo: self.topAnchor).isActive = true
contentView.bottomAnchor.constraint(equalTo: self.bottomAnchor).isActive = true
contentView.widthAnchor.constraint(equalTo: self.widthAnchor, multiplier: CGFloat(19), constant: CGFloat(5)).isActive = true
contentView.heightAnchor.constraint(equalTo: self.heightAnchor, multiplier: 2.0, constant: CGFloat(5)).isActive = true
// self.contentSize = CGSize(width: 10000, height: 2*frame.height)
let subviewWidth = CGFloat(450)
let subviewHeight = CGFloat(20)
//Add other subviews to contentView
(0...4).compactMap { i in
(0...19).compactMap { j in
let x = CGFloat(j)*(subviewWidth + 5.0) + 5.0
let y = CGFloat(i)*(subviewHeight + 5.0) + 5.0
let subview = UIView(frame: CGRect(x: x, y: y, width: subviewWidth, height: subviewHeight))
contentView.addSubview(subview)
}
}
问题是当自动布局约束如上所述设置时,滚动视图不会滚动。如果没有设置约束,它会滚动,但在缩放后,滚动会再次被禁用。我只是在滚动视图委托中设置了这个。
public func viewForZooming(in scrollView: UIScrollView) -> UIView? {
return scrollView.subviews.first //contentView
}
【问题讨论】:
-
做一些额外的搜索/研究以了解
UIScrollView的工作原理。如果您为滚动视图的内容使用自动布局(您应该这样做),您永远不想设置.contentSize——这是错误的。 -
好的,我需要在向 UIScrollView 添加更多子视图时动态更改 contentView 的宽度和高度锚点。但是现在似乎 contentSize 在我设置约束时没有立即更新。由于各种原因,我需要查询 contentSize 属性。我需要等待查询吗?
-
要获得这方面的帮助,您需要显示一些代码。 “当我添加更多子视图时,我需要动态改变 contentView 的宽度和高度锚点” ...这是一项非常常见的任务...你是怎么做到的?添加子视图时是否正确更改约束?没有看到你在做什么(你的代码),就没有办法告诉你你做错了什么。
-
我更新了问题。截至目前,我只是按照所示方式在循环中添加子视图。稍后,我会动态添加或删除这些子视图。
-
那么...您没有为要添加的子视图使用自动布局吗?
标签: ios swift uiscrollview autolayout