加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

swift – UISwipeGestureRecognizer无法识别视图外部启动的滑动

发布时间:2020-12-14 04:36:14 所属栏目:百科 来源:网络整理
导读:func addSwipe() { self.isUserInteractionEnabled = true let directions: [UISwipeGestureRecognizerDirection] = [.right,.left] for direction in directions { let gesture = UISwipeGestureRecognizer(target: self,action: #selector(ViewCardContain
func addSwipe() {
    self.isUserInteractionEnabled = true
    let directions: [UISwipeGestureRecognizerDirection] = [.right,.left]
    for direction in directions {
        let gesture = UISwipeGestureRecognizer(target: self,action: #selector(ViewCardContainer.handleSwipe(sender:)))
        gesture.direction = direction
        self.addGestureRecognizer(gesture)
    }
}

@objc func handleSwipe(sender: UISwipeGestureRecognizer) {
    print(sender.direction)
}

我的UIViews:

+----------------+
|                |
|     +--------+ |
|  V1 |  V2    | |
+-----------------

我在V2中注册了UISwipeGestureRecognizer但是如果从V1开始通过V2启动滑动手势,则在V2中将无法识别滑动手势.

反正有没有让它工作?提前致谢!

解决方法

编辑:我为你做了一个工作示例项目.您可以从红色方块(v1)滑动到蓝色方块(v2),并在日志中看到检测到滑动.

https://github.com/QuantumProductions/so_46781856

import UIKit

class ViewController: UIViewController {
    var view2: UIView!

    override func viewDidLoad() {
        super.viewDidLoad()

        view.backgroundColor = UIColor.black

        let view1 = UIView(frame: CGRect(x: 0,y: 0,width: 100,height: 100))
        view1.backgroundColor = UIColor.red
        view.addSubview(view1)

        view2 = UIView(frame: CGRect(x: 100,height: 100))
        view2.backgroundColor = UIColor.blue
        view.addSubview(view2)

        let swipeRecognizer = UISwipeGestureRecognizer(target: self,action: #selector(swipeDetected(_:)))
        swipeRecognizer.direction = .right
        view.addGestureRecognizer(swipeRecognizer)

    }

    func swipeDetected(_ sender: UIGestureRecognizer) {
        let location = sender.location(ofTouch: 0,in: view2)
        print("Location in view2")
        print(location)
        print("You swiped right")
    }
}

原答案:

这是故意的.滑动检测基于视图查看.尝试像联系人这样的Apple应用程序,你会发现从滚动视图中向上移动手指后,你无法按下导航栏中的按钮.

如果您希望触摸识别器在V1和V2中有效:

>在V1和EX的父视图中添加手势识别器. V2
>检测触摸是否在V2的矩形内(使用touch.locationInView:V2)
>如果为true,请运行预期的功能

如果这是一个viewcontroller,你需要将识别器添加到self.view(从你的例子中不清楚识别器添加到哪个视图,因为没有关于你的func所在的类的上下文)

您可能需要禁用V1和V2上的用户交互,如果它正在吃掉触摸并在父视图上保持启用状态.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读