RxSwift之UI控件UIGestureRecognizer扩展的使用

  • RxCocoa 同样对 UIGestureRecognizer 进行了扩展,并增加相关的响应方法。现在以滑动手势为例做具体说明,其它手势用法也是一样的。
  • 当手指在界面上向上滑动时,弹出提示框,并显示出滑动起点的坐标,效果如下:

在这里插入图片描述

  • 响应回调的示例一:
// 添加一个上滑手势
let swipe = UISwipeGestureRecognizer()
swipe.direction = .up
self.view.addGestureRecognizer(swipe)

// 手势响应
swipe.rx.event
   .subscribe(onNext: {
    
     [weak self] recognizer in
       // 滑动的起点
       let point = recognizer.location(in: recognizer.view)
       self?.showAlert(title: "向上划动", message: "\(point.x) \(point.y)")
   })
   .disposed(by: disposeBag)

// 显示消息提示框
func showAlert(title: String, message: String) {
    
    
   let alert = UIAlertController(title: title, message: message,
                                 preferredStyle: .alert)
   alert.addAction(UIAlertAction(title: "确定", style: .cancel))
   self.present(alert, animated: true)
}
  • 响应回调的示例二:
// 添加一个上滑手势
let swipe = UISwipeGestureRecognizer()
swipe.direction = .up
self.view.addGestureRecognizer(swipe)
 
// 手势响应
swipe.rx.event
    .bind {
    
     [weak self] recognizer in
        let point = recognizer.location(in: recognizer.view)
        self?.showAlert(title: "向上划动", message: "\(point.x) \(point.y)")
    }
    .disposed(by: disposeBag)

猜你喜欢

转载自blog.csdn.net/Forever_wj/article/details/121308695