本文介绍了无法使用自定义DelegateProxy和协议接收事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我尝试将DifficultyViewDelegate的委托迁移到可观察的.这是我的DifficultyViewDelegate:
I try to migrate delegate of DifficultyViewDelegate to observable. This is my DifficultyViewDelegate :
@objc protocol DifficultyViewDelegate: class {
func levelDidIncrease()
func levelDidDecrease()
}
我的DifficultyView:
And my DifficultyView :
weak var delegate: DifficultyViewDelegate?
@IBAction func decreaseLevel(_ sender: Any) {
delegate?.levelDidDecrease()
}
@IBAction func increaseLevel(_ sender: Any) {
delegate?.levelDidIncrease()
}
这是我的RxDifficultyViewDelegateProxy
And this is my RxDifficultyViewDelegateProxy
class RxDifficultyViewDelegateProxy: DelegateProxy, DelegateProxyType {
static func currentDelegateFor(_ object: AnyObject) -> AnyObject? {
let difficultyView: DifficultyView = object as! DifficultyView
return difficultyView.delegate
}
static func setCurrentDelegate(_ delegate: AnyObject?, toObject object: AnyObject) {
let difficultyView: DifficultyView = object as! DifficultyView
difficultyView.delegate = delegate as? DifficultyViewDelegate
}
}
我还在DifficultyView上添加了扩展名:
I also added an extension on my DifficultyView :
extension DifficultyView {
public var rx_delegate: RxDifficultyViewDelegateProxy {
return RxDifficultyViewDelegateProxy.proxyForObject(RxDifficultyViewDelegateProxy.self)
}
public var rx_levelDidIncrease: Observable<Void> {
return rx_delegate.methodInvoked(#selector(DifficultyViewDelegate.levelDidIncrease)).map { _ in return }
}
}
但是,当我这样做时:
difficultyView.rx_levelDidIncrease.asObservable().subscribe(onNext: {
print("did increase")
}).addDisposableTo(disposeBag)
它从未被调用过.有人有指针吗?
It's never called. Someone has any pointers ?
推荐答案
尝试使用PublishSubject
:
DifficultyView:
DifficultyView:
class DifficultyView: UIView {
var levelDidIncrease = PublishSubject<Void>()
var levelDidDecrease = PublishSubject<Void>()
@IBAction func decreaseLevel(_ sender: Any) {
levelDidDecrease.onNext()
}
@IBAction func increaseLevel(_ sender: Any) {
levelDidIncrease.onNext()
}
}
然后:
var difficultyView = DifficultyView()
difficultyView.levelDidDecrease.asObservable()
.subscribe(onNext: {
print("did decrease")
})
.addDisposableTo(disposeBag)
difficultyView.decreaseLevel(theSender) // <- THIS line performs the side effect
这篇关于无法使用自定义DelegateProxy和协议接收事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!