我正在子类化UIScrollView中添加一些功能,例如双击缩放和用于图库目的的image属性。但是为了做图像部分,我的子类必须是自己的委托并实现viewForZoomingInScrollView。
UIScrollView
viewForZoomingInScrollView
但是,当有人使用我的滚动视图子类时,他们可能还希望获得委托通知,以查看scrollViewDidScroll或了解您的情况。
scrollViewDidScroll
在Swift中,我如何同时获得这两个?
这是此模式的Swift版本:
尽管forwardInvocation:已在Swift中禁用,但我们仍然可以使用forwardingTargetForSelector:
forwardInvocation:
forwardingTargetForSelector:
class MyScrollView: UIScrollView { class _DelegateProxy: NSObject, UIScrollViewDelegate { weak var _userDelegate: UIScrollViewDelegate? override func respondsToSelector(aSelector: Selector) -> Bool { return super.respondsToSelector(aSelector) || _userDelegate?.respondsToSelector(aSelector) == true } override func forwardingTargetForSelector(aSelector: Selector) -> AnyObject? { if _userDelegate?.respondsToSelector(aSelector) == true { return _userDelegate } else { return super.forwardingTargetForSelector(aSelector) } } func viewForZoomingInScrollView(scrollView: MyScrollView) -> UIView? { return scrollView.viewForZooming() } // Just a demo. You don't need this. func scrollViewDidScroll(scrollView: MyScrollView) { scrollView.didScroll() _userDelegate?.scrollViewDidScroll?(scrollView) } } private var _delegateProxy = _DelegateProxy() required init(coder aDecoder: NSCoder) { super.init(coder: aDecoder) super.delegate = _delegateProxy } override init(frame: CGRect) { super.init(frame: frame) super.delegate = _delegateProxy } override var delegate:UIScrollViewDelegate? { get { return _delegateProxy._userDelegate } set { self._delegateProxy._userDelegate = newValue; /* It seems, we don't need this anymore. super.delegate = nil super.delegate = _delegateProxy */ } } func viewForZooming() -> UIView? { println("self viewForZooming") return self.subviews.first as? UIView // whatever } func didScroll() { println("self didScroll") } }