OGeek|极客世界-中国程序员成长平台

标题: IOS:如何仅在 subview 之外触摸时滚动 ScrollView ? [打印本页]

作者: 菜鸟教程小白    时间: 2022-12-11 18:05
标题: IOS:如何仅在 subview 之外触摸时滚动 ScrollView ?

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

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)
    }
}

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

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

    override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
        self.isScrollEnabled = true
    }

    override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
        self.isScrollEnabled = true
    }
}

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

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

干杯,感谢任何帮助。



Best Answer-推荐答案


可能最简单的方法是将虚拟 UIPanGestureRecognizer 添加到蓝色 View 中,如下所示:

blueView.addGestureRecognizer(UIPanGestureRecognizer())

即使没有 Action ,这也能完成工作,因为触摸将首先由 subview 处理,然后才由 UIScrollView 自己的 UIPagGestureRecognizer 处理。

关于IOS:如何仅在 subview 之外触摸时滚动 ScrollView ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40638863/






欢迎光临 OGeek|极客世界-中国程序员成长平台 (http://ogeek.cn/) Powered by Discuz! X3.4