我的 View Controller 中有一个 UIScrollView
,其中有一个 UIView
(称为 viewPreSeasonCard
)作为内容 View ,所有操作都在界面生成器。然后我以编程方式将 subview 添加到容器中,如下所示:
func displayPreSeason(preSeasons: [PreSeason]) {
var yPos = 0
let viewWidth = Int(viewPreSeasonCard.frame.width)
for (index, preSeason) in preSeasons.enumerated() {
yPos = 40 + index * 80
let frame = CGRect(x: 0, y: yPos, width: viewWidth, height: 78)
let preSeasonView = PreSeasonLineupView(frame: frame)
preSeasonView.setPreSeason(preSeason: preSeason)
preSeasonView.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(self.preSeasonClicked)))
viewPreSeasonCard.frame.size.height += frame.height
viewPreSeasonCard.addSubview(preSeasonView)
}
let curSize = self.view.frame
scrollView.contentSize = CGSize(width: curSize.width, height: curSize.height + CGFloat(yPos))
}
如您所见,我在添加 subview 后调整 scrollView.contentSize
。这一切都正常工作,我可以一直向下滚动 ScrollView 并查看所有 subview 。
问题出在我添加到 subview 的 UITapGestureRecognizer
上。当 subview 最初在设备屏幕上可见时(即前 3 或 4 个 subview ),手势识别器正在工作。但是当我必须滚动查看 subview 时,当我点击它们时,这些 subview 上的手势识别器根本不会触发。就好像因为较低的 subview 最初是不可见的,所以手势识别器被忽略了。
这是手势识别器的方法:
func preSeasonClicked(_ sender: UITapGestureRecognizer) {
if let preSeasonView = gestureRecognizer.view as? PreSeasonLineupView, let constructorId = preSeasonView.constructorId {
presenter.preSeasonClicked(constructorId: constructorId)
}
}
最佳答案
我有同样的问题,我在 ScrollView 中有 ContentView
问题我发现我设置的ContentView 的高度等于ScrollView 的父 View 。我正在自己计算 ScrollView 的 ContentSize。
所以行为是 ScrollView 正确滚动,但在 ViewController 的第一次显示中任何 View 都关闭屏幕无法检测到触摸。
经过一些调试后,我尝试使 ContentView 的 ClipToBounds 为真。我看到了我在等什么,内容 View 只有屏幕的高度(ScrollView 父级)
我删除了使内容 View 与 ScrollView 父级高度相等的约束。 而不是添加新的约束以将容器 View 的底部与底部的大多数 View 的底部对齐,并且不再计算内容大小。
目前滚动工作正常,触摸工作适用于所有 View 。
关于ios - 当 ScrollView subview 不在屏幕上时手势识别器不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42490279/