我为UICollectionView编写了一个扩展,它将侦听委托的shouldHighlightItemAt方法,但它不会调用。
public var shouldHighlightItem: ControlEvent<IndexPath> {
let source = self.delegate.methodInvoked(#selector(UICollectionViewDelegate.collectionView(_:shouldHighlightItemAt:)))
.map { a in
return try self.castOrThrow(IndexPath.self, a[1])
}
return ControlEvent(events: source)
}}
如何为UICollectionView of rx shouldHighlightItemAt编写扩展?
发布于 2018-11-04 18:24:26
不能将methodInvoked(_:)与具有非空返回类型的委托方法一起使用。
collectionView(_:shouldHighlightItemAt:)希望您返回一个Bool值。所以您不能使用methodInvoked(_:)。
如果您看一下methodInvoked(_:)的实现,它会给出为什么不起作用的解释:
不能使用此方法直接观察具有非
void返回值的委托方法,因为:
然而,有一个建议是,你如何才能实现你想要做的事情:
如果需要观察具有返回类型的委托方法,则可以手动安装
PublishSubject或BehaviorSubject并实现委托方法。
在你的例子中,它是这样工作的:
在RxCollectionViewDelegateProxy UICollectionViewDelegate 中添加“PublishSubject”并实现UICollectionViewDelegate方法:
let shouldHighlightItemAtIndexPathSubject = PublishSubject<IndexPath>
public func collectionView(_ collectionView: UICollectionView, shouldHighlightItemAt indexPath: IndexPath) -> Bool {
shouldHighlightItemAtIndexPathSubject.on(.next(indexPath))
return self._forwardToDelegate?.collectionView(collectionView, shouldHighlightItemAt: indexPath) ?? true // default value
}在您的UICollectionView RxExtension中,您可以像下面这样公开所需的可观察到的内容:
public var property: Observable<IndexPath> {
let proxy = RxCollectionViewDelegateProxy.proxy(for: base)
return proxy.shouldHighlightItemAtIndexPathSubject.asObservable()
}我还没有对此进行测试,我只是从RxCocoa源代码中提取并修改了它,以满足您的需要。因此,从理论上讲,这是可行的,但您可能需要稍微调整一下;-)
https://stackoverflow.com/questions/53142723
复制相似问题