Last active
December 12, 2018 10:16
-
-
Save sakiwei/2a5633f8fa45cdaf9285695bb82922ff to your computer and use it in GitHub Desktop.
A sample of creating custom delegate for RxSwift [Reference: http://blog.edenmsg.com/rxswift-migrate-delegates-to-beautiful-observables/]
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import TTTAttributedLabel | |
import RxSwift | |
import RxCocoa | |
fileprivate class RxTTTAttributedLabelDelegateProxy: DelegateProxy, TTTAttributedLabelDelegate, DelegateProxyType { | |
//We need a way to read the current delegate | |
static func currentDelegateFor(_ object: AnyObject) -> AnyObject? { | |
let label: TTTAttributedLabel = object as! TTTAttributedLabel | |
return label.delegate | |
} | |
//We need a way to set the current delegate | |
static func setCurrentDelegate(_ delegate: AnyObject?, toObject object: AnyObject) { | |
let label: TTTAttributedLabel = object as! TTTAttributedLabel | |
label.delegate = delegate as? TTTAttributedLabelDelegate | |
} | |
} | |
extension Reactive where Base : TTTAttributedLabel { | |
var delegate: DelegateProxy { | |
return RxTTTAttributedLabelDelegateProxy.proxyForObject(base) | |
} | |
var linkDidTap: Observable<URL> { | |
let selector = #selector( | |
((TTTAttributedLabelDelegate.attributedLabel(_:didSelectLinkWith:))! | |
as (TTTAttributedLabelDelegate) -> (TTTAttributedLabel, URL) -> Void)) | |
return delegate.observe(selector) | |
.map { params in | |
return params[1] as! URL | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
When you face a problem of ambiguous use of a selector, you should read this article https://www.bignerdranch.com/blog/hannibal-selector/.
Swift selector is a bit tricky :-)