I have a label
with isUserInteractionEnabled
set to true
. Now, I need to add UITapGestureRecognizer
for the label. Is there a way to add in Rx
way.
I have looked at the RxSwift library here. Which they didn't provide any extension for adding gesture. The UILabel+Rx
file has only text
and attributedText
.
Is there any workaround to add gesture to label?
An image is commonly displayed by a UIImageView instance, which means we add a gesture recognizer to the image view ( UIImageView ), not the image ( UIImage ). Fire up Xcode and create a blank project by choosing the App template from the iOS > Application section. Name the project Tappable, set Interface to Storyboard, and Language to Swift.
Open Main.storyboard and drag a tap gesture recognizer from the Object Library and drop it onto the image view we added earlier. The tap gesture recognizer appears in the Document Outline on the left. We need to implement an action that defines what happens when the user taps the image view.
I always add gesture recognizers in code, but that is a personal choice. Let's start with Interface Builder. Open Main.storyboard and drag a tap gesture recognizer from the Object Library and drop it onto the image view we added earlier. The tap gesture recognizer appears in the Document Outline on the left.
It accepts the tap gesture recognizer as its only argument. Open Main.storyboard and select the tap gesture recognizer in the Document Outline. Open the Connections Inspector on the right and drag from selector in the Sent Actions section to the view controller in the Document Outline.
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)
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!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With