菜鸟教程小白 发表于 2022-12-11 19:05:06

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


                                            <p><p>我的 ViewController 中有一个 <code>UIScrollView</code>,其中有一个 <code>UIView</code>(称为 <code>viewPreSeasonCard</code>)作为内容 View ,全部在界面生成器。然后我以编程方式将 subview 添加到容器中,如下所示:</p>

<pre><code>func displayPreSeason(preSeasons: ) {
    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))
}
</code></pre>

<p>如您所见,我在添加 subview 后调整 <code>scrollView.contentSize</code>。这一切正常,我可以一直向下滚动 ScrollView 并查看所有 subview 。 </p>

<p>问题在于我要添加到 subview 中的 <code>UITapGestureRecognizer</code>。当 subview 最初在设备屏幕上可见时(即前 3 或 4 个 subview ),手势识别器正在工作。但是当我必须滚动查看 subview 时,当我点击它们时,这些 subview 上的手势识别器根本不会触发。好像是因为最初看不到较低的 subview ,所以忽略了手势识别器。</p>

<p>手势识别器的方法如下:</p>

<pre><code>func preSeasonClicked(_ sender: UITapGestureRecognizer) {
    if let preSeasonView = gestureRecognizer.view as? PreSeasonLineupView, let constructorId = preSeasonView.constructorId {
      presenter.preSeasonClicked(constructorId: constructorId)
    }
}
</code></pre></p>
                                    <br><hr><h1><strong>Best Answer-推荐答案</ strong></h1><br>
                                            <p><p>我有同样的问题,我在 ScrollView 中有 ContentView</p>

<p>我发现的问题是我设置的 ContentView 其高度等于 ScrollView 父 View 。我正在计算自己的 ScrollView 的 ContentSize。</p>

<p>所以行为是 ScrollView 正确滚动,但任何 View 在 ViewController 的第一次显示中都处于关闭屏幕无法检测到触摸。</p>

<p>经过一些调试后,我尝试使 ClipToBounds 对 ContentView 是正确的。我看到了我在等待的内容,内容 View 只有屏幕的高度(ScrollView 父级)</p>

<p>我删除了使内容 View 等于 ScrollView 父级高度的约束。
而不是添加了新的约束来将容器 View 的底部与底部大多数 View 的底部对齐,并且不再计算内容大小。</p>

<p>目前滚动工作正常,触摸适用于所有 View 。</p></p>
                                   
                                                <p style="font-size: 20px;">关于ios - 当 ScrollViewsubview 不在屏幕上时,手势识别器不起作用,我们在Stack Overflow上找到一个类似的问题:
                                                        <a href="https://stackoverflow.com/questions/42490279/" rel="noreferrer noopener nofollow" style="color: red;">
                                                                https://stackoverflow.com/questions/42490279/
                                                        </a>
                                                </p>
                                       
页: [1]
查看完整版本: ios - 当 ScrollView subview 不在屏幕上时,手势识别器不起作用