今天講GitHub - RxSwiftCommunity/RxGesture,RxGesture是封裝UIGestureRecognizer
的方法,幫助我們在任何view上面進行各種手勢的偵測。
在遇到RxGesture之前,我是這樣寫
let myView: UIView = UIView()
let tapGesture = UITapGestureRecognizer()
myView.addGestureRecognizer(tapGesture)
tapGesture.rx.event
.debug("Tap")
.subscribe()
.disposed(by: disposeBag)
建立一個UITapGestureRecognizer()
,給myView
加入手勢的識別,在用Rx的方式監聽手勢的事件。
當我遇到RxGesture之後,我變成這樣寫
let myView: UIView = UIView()
myView.rx.tapGesture()
.when(.recognized)
.debug("Tap")
.subscribe()
.disposed(by: disposeBag)
myView
擴充了tap
手勢的事件,when
可以幫助我們過濾UIGestureRecognizerState
,使用時監聽即可。
以下就記錄一下常用的手勢,假設我有一個UIView叫做myView
let myView = UIView(frame: .zero)
self.view.addSubview(myView)
myView.snp.makeConstraints { make in
make.width.height.equalTo(200)
make.center.equalToSuperview()
}
Tap 點一下
myView.rx.tapGesture()
.when(.recognized)
.subscribe(onNext: { _ in
print("Tap")
})
.disposed(by: disposeBag)
Double Click 點兩下
myView.rx.tapGesture() { gesture, _ in
gesture.numberOfTapsRequired = 2
}
.when(.recognized)
.subscribe(onNext: { _ in
print("Double Click")
})
.disposed(by: disposeBag)
Long Press 長按
myView.rx.longPressGesture()
.when(.began)
.subscribe(onNext: { _ in
print("Long Press")
})
.disposed(by: disposeBag)
Pan 拖移
myView.rx.panGesture()
.when(.began, .changed, .ended)
.subscribe(onNext: {
$0.view?.center = $0.location(in: self.view)
print("panGesture: \($0.state)")
})
.disposed(by: disposeBag)
Swipe 滑動
myView.rx.swipeGesture(.up, .down)
.when(.recognized)
.subscribe(onNext: {
print("Swipe \($0.direction.rawValue)")
})
.disposed(by: disposeBag)
Pinch 縮放
myView.rx.pinchGesture()
.when(.began, .changed, .ended)
.subscribe(onNext: {
$0.view?.transform = CGAffineTransform(scaleX: $0.scale, y: $0.scale)
print("Pinch \($0.scale)")
})
.disposed(by: disposeBag)
Rotation 旋轉
myView.rx.rotationGesture()
.when(.began, .changed, .ended)
.subscribe(onNext: {
let angle = $0.rotation * (180 / CGFloat(Double.pi))
$0.view?.transform = CGAffineTransform(rotationAngle: $0.rotation)
print("Rotation: \($0.state), \(angle)")
})
.disposed(by: disposeBag)
以上,就是今天介紹RxGesture的內容,原本對手勢沒到很了解,工作上也不太接觸,反倒是趁這機會接觸了一下,滿有趣的
倒數兩天,相處時間不多了,明天見囉,大家掰掰