菜鸟教程小白 发表于 2022-12-11 18:05:08

IOS:如何仅在 subview 之外触摸时滚动 ScrollView ?


                                            <p><p>我有一个 ScrollView ,里面有一个 subview 。我希望 subview 之外的任何触摸都可以使 ScrollView 像在任何其他情况下一样滚动。但是当触摸在 subview 内时,我不想注册滚动(所以我可以使用该触摸进行拖动)。</p>

<pre><code>class ViewController: UIViewController {
    @IBOutlet weak var scrollView: UIScrollView!

    override func viewDidLoad() {
      super.viewDidLoad()
      scrollView.backgroundColor = UIColor.red
      scrollView.contentSize = CGSize(width: 1000, height: 1000)
      let view = UIView(frame: CGRect(x: 600, y: 600, width: 200, height: 200))
      view.backgroundColor = UIColor.blue
      scrollView.addSubview(view)
    }
}
</code></pre>

<hr/>

<p>到目前为止,我已经尝试了很多方法来完成这项工作。我在为 subview 和 ScrollView 制作海关类方面取得了一些成功。在这些类中,我像这样覆盖触摸方法:</p>

<pre><code>class MyScrollView: UIScrollView {
    override func touchesBegan(_ touches: Set&lt;UITouch&gt;, with event: UIEvent?) {
      self.isScrollEnabled = true
    }

    override func touchesMoved(_ touches: Set&lt;UITouch&gt;, with event: UIEvent?) {
      self.isScrollEnabled = true
    }

    override func touchesEnded(_ touches: Set&lt;UITouch&gt;, with event: UIEvent?) {
      self.isScrollEnabled = true
    }
}
</code></pre>

<p>对于 ScrollView 自定义类,我打开了滚动,然后对于 subview 自定义类,我将其关闭。这可行,但有一个主要问题是在 isScrollEnabled 更改之前第一次触摸仍然进行。这意味着当滚动关闭并且您想要滚动时,您必须触摸框外并且没有任何反应,然后进行相同的触摸并开始触摸。</p>

<p>我正在寻找的是一种实现触摸位置的方法,更改滚动设置,然后在同一触摸上仍然滚动或不滚动,具体取决于设置是什么。 </p>

<p>干杯,感谢任何帮助。</p></p>
                                    <br><hr><h1><strong>Best Answer-推荐答案</ strong></h1><br>
                                            <p><p>可能最简单的方法是将虚拟 <code>UIPanGestureRecognizer</code> 添加到蓝色 View 中,如下所示:</p>

<pre><code>blueView.addGestureRecognizer(UIPanGestureRecognizer())
</code></pre>

<p>即使没有 Action ,这也能完成工作,因为触摸将首先由 subview 处理,然后才由 <code>UIScrollView</code> 自己的 <code>UIPagGestureRecognizer</code> 处理。 </p></p>
                                   
                                                <p style="font-size: 20px;">关于IOS:如何仅在 subview 之外触摸时滚动 ScrollView ?,我们在Stack Overflow上找到一个类似的问题:
                                                        <a href="https://stackoverflow.com/questions/40638863/" rel="noreferrer noopener nofollow" style="color: red;">
                                                                https://stackoverflow.com/questions/40638863/
                                                        </a>
                                                </p>
                                       
页: [1]
查看完整版本: IOS:如何仅在 subview 之外触摸时滚动 ScrollView ?