ios - 当 ScrollView subview 不在屏幕上时手势识别器不工作

标签 ios swift uiscrollview uitapgesturerecognizer

我的 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/

相关文章:

ios - 在编辑 UITableViewCell 时更改标签颜色

uitableview - 确定 UIWebView 内容的高度(嵌入 UITableViewCell 中)

ios - UIButtons 在直接添加到 ScrollView 但不是间接添加时接收触摸事件

ios - ScrollView 栏滚动,而 Content View 不滚动

iphone - UIFileSharingEnabled 使用文件夹

iPhone : Implement Ole Leaves API

ios - 更新位置时 map View 跨度发生变化

ios - 无法使用类型为 'String' 的参数列表调用类型为 '(CustomObject)' 的初始值设定项

Swift 4 : Find value in nested, 动态字典 <String, Any> 递归

ios - 检测一个 UIView 何时位于另一个 UIView 之上