RxSwift: How to add gesture to UILabel?
Swift 5 (using RxGesture library).
Best and simplest option imho.
label
.rx
.tapGesture()
.when(.recognized) // This is important!
.subscribe(onNext: { [weak self] _ in
guard let self = self else { return }
self.doWhatYouNeedToDo()
})
.disposed(by: disposeBag)
Take care! If you don't use .when(.recognized)
the tap gesture will fire as soon as your label is initialised!
A UILabel is not configured with a tap gesture recognizer out of the box, that's why RxCocoa does not provide the means to listen to a gesture directly on the label. You will have to add the gesture recognizer yourself. Then you can use Rx to observe events from the recognizer, like so:
let disposeBag = DisposeBag()
let label = UILabel()
label.text = "Hello World!"
let tapGesture = UITapGestureRecognizer()
label.addGestureRecognizer(tapGesture)
tapGesture.rx.event.bind(onNext: { recognizer in
print("touches: \(recognizer.numberOfTouches)") //or whatever you like
}).disposed(by: disposeBag)