I'm subclassing UIScrollView
to add some features such as double tap to zoom and an image property for gallery purposes. But in order to do the image part my subclass has to be its own delegate and implement the viewForZoomingInScrollView
.
But then when someone uses my scroll view subclass, they might like to get delegate notifications as well to see scrollViewDidScroll
or what have you.
In Swift, how do I get both of these?
Here is a Swift version of this pattern:
Although
forwardInvocation:
is disabled in Swift, we can still useforwardingTargetForSelector:
I don't know about any 100% Swift solution for this. Taking this ObjC answer to the same problem, and trying to port it to Swift it turns out that is not possible since NSInvocation is not available in Swift.
What we can do is to implement the suggested MyScrollViewPrivateDelegate in ObjC(don't forget to import it in the bridging header file) and the scroll view subclass in Swift like the following:
MyScrollView.swift
MyScrollViewPrivateDelegate.h
MyScrollViewPrivateDelegate.m
Here's a simple working Playground version in Swift 3 that acts purely as an observer rather than only as an interceptor like the other answers here.
The distinction is that the original scroll view delegate should have all of its delegate methods called like normal versus them being hijacked by another delegate.
(You can copy/paste this into a playground and run it to test)
This prints