Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RxSwift wrapper for textView:shouldInteractWithURL:inRange:interaction:

I want to have a method to intercept links tap in a UITextView through RxSwift something similar to:

textView.rx.didTapLink
        .subscribe(onNext: { link, characterRange, interaction in
            // handle link tap
        })

I saw there is no implementation for delegate forwarding for the textView:shouldInteractWithURL:inRange:interaction: method so I presume I must add an extension for the RxTextViewDelegateProxy to implement the missing delegate method but don't know how to continue from there or if what I want is event possible without forking RxSwift but it should be possible I presume. I really appreciate any help.

like image 478
Bogdan Avatar asked Jul 30 '26 09:07

Bogdan


1 Answers

Because the method in question returns a value (the OS pulls data from your app using this method,) it doesn't fit well with the Rx "push data" ecosystem. The appropriate way to implement this is as follows:

Given:

class MyTextViewDelegate: NSObject, UITextViewDelegate {
    func textView(_ textView: UITextView, shouldInteractWith url: URL, in characterRange: NSRange, interaction: UITextItemInteraction) -> Bool {
        return true // do what you think best here.
    }
}

You can connect it to the text view like this:

textView.rx.delegate.setForwardToDelegate(MyTextViewDelegate(), retainDelegate: true)

Using the forwardToDelegate allows you to continue to use the push type delegate methods using the Rx system.

like image 66
Daniel T. Avatar answered Aug 01 '26 22:08

Daniel T.