Sasha Sasha - 2 months ago 20
iOS Question

Tracking swipe movement in Swift

I'm very new to Swift, and trying to create an app where Swiping between pages works normally but also involves a change in background color based on swipe distance.

Consequently, I want to "hijack" the swipe gesture, so I can add some behavior to it. The best I can find for how to do that is this question/answer.

Translating the code from the chosen answer into Swift 3, I added the following code to my


for subview in (pageViewController?.view.subviews)!{
if let coercedView = subview as? UIScrollView {
coercedView.delegate = (self as! UIScrollViewDelegate)

My impression was that the above code would let me
functions (such as
to the class in which I'm writing the above code, such that I can define that function, call
, and then add any other functionality I want.

Unfortunately, the above code, which doesn't throw any compilation errors, does throw an error when I try to build the app:

Could not cast value of type 'My_App.RootViewController' (0x102cbf740) to 'UIScrollViewDelegate' (0x1052b2b00).

Moreover, when I try to write
override func scrollViewDidScroll
in my class, I get a compilation error telling me the function doesn't exist to override, which makes me think even if I got past the error, it wouldn't get called, and this isn't the right way to handle this issue.

I'm sorry this is such a noobish question, but I'm really quite confused about the basic architecture of how to solve this, and whether I understand the given answer correctly, and what's going wrong.

Am I interpreting
and that answer correctly?
Am I delegating to the correct object? (Is that the right terminology here?)
Is there a better way to handle this?
Am I coercing/casting improperly? Should I instead do:

view.delegate = (SomeHandMadeViewDelegateWhichDefinesScrollViewDidScroll as! UIScrollViewDelegate)

or something similar/different (another nested casting with
let coercedSelf = self as? UIScrollViewDelegate
or something?



If I understand your question correctly, you want to catch some scroll position and stuff right ? Then do

class RootViewController {
   // Your stuff

   for subview in (pageViewController?.view.subviews)!{
     if let coercedView = subview as? UIScrollView {
      coercedView.delegate = self

extension RootViewController : UIScrollViewDelegate {
   // Your scrollView stuff there