Skip to content

Instantly share code, notes, and snippets.

@sakiwei
Last active December 12, 2018 10:16
Show Gist options
  • Save sakiwei/2a5633f8fa45cdaf9285695bb82922ff to your computer and use it in GitHub Desktop.
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/]
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
}
}
}
@sakiwei
Copy link
Author

sakiwei commented Sep 29, 2016

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 :-)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment