RxSwift: How to add a gesture to UILabel?

I have labelwith isUserInteractionEnabledinstalled in true. Now I need to add UITapGestureRecognizerfor the tag. Is there a way to add to the Rxmethod.

I looked at the RxSwift library here . Which they did not provide any extension to add a gesture. UILabel+Rxonly has textand attributedText text.

Is there a workaround to add a gesture to the shortcut?

+12
source share
4 answers

UILabel is not configured with a gesture recognizer, which is why RxCocoa does not provide a means to listen for gestures directly on the shortcut. You will have to add a gesture recognizer yourself. Then you can use Rx to observe events from the resolver, for example:

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)
+36
source

Swift 4 with RxCocoa + RxSwift + RxGesture

let disposeBag = DisposeBag()
let myView = UIView()

myView.rx
  .longPressGesture(numberOfTouchesRequired: 1,
                    numberOfTapsRequired: 0,
                    minimumPressDuration: 0.01,
                    allowableMovement: 1.0)
            .when(.began, .changed, .ended)
            .subscribe(onNext: { pan in
                let view = pan.view
                let location = pan.location(in: view)
                switch pan.state {
                case .began:
                    print("began")
                case .changed:
                    print("changed \(location)")
                case .ended:
                    print("ended")
                default:
                    break
                }
            }).disposed(by bag)

or

myView.rx
.gesture(.tap(), .pan(), .swipe([.up, .down]))
.subscribe({ onNext: gesture in
    switch gesture {
    case .tap: // Do something
    case .pan: // Do something
    case .swipeUp: // Do something 
    default: break       
    }        
}).disposed(by: bag)

or an event smart to return the event. those. line

var buttons: Observable<[UIButton]>!

let stringEvents = buttons
        .flatMapLatest({ Observable.merge($0.map({ button in
            return button.rx.tapGesture().when(.recognized)
                .map({ _ in return "tap" })
            }) )
        })
+9
source

RxCocoa, RxSwift.

UITapGestureRecognizer , rx.event(rx_event, ) .

If you need to do this in the context of UILabel, you might also need to wrap it inside UILabel + Rx, but if you have simpler requirements, just using rx.event on a gesture should be a good workaround.

+1
source

You can sign a touch gesture shortcut.

    label
        .rx
        .tapGesture()
        .subscribe(onNext: { _ in
            print("tap")
        }).disposed(by: disposeBag)
0
source

Source: https://habr.com/ru/post/1679631/


All Articles