Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extending UIScrollView and Monitoring Scroll Events

I'm wanting to implement some custom, reusable and efficient scroll behavior in an iPhone app so I'm extending UIScrollView with my custom control and wish to track scroll movements.

Now I'm aware that I could probably assign my custom control as a UIScrollViewDelegate and internally respond to scrollViewDidScroll calls but this doesn't feel correct to me (I may be wrong).

It doesn't feel correct as the delegate is aimed at application specific UI logic and controls should be a level above this. It would also mean I'd need to relay delegate calls out if an application class assigned itself as a delegate too which seems inefficient.

As a direct descendant of UIScrollView I'd expect to be able to override the method that triggers the scrollViewDidScroll delegate call, or be given access to a template method, or listen out for scroll events, but I can't see any such options.

Looking at the UITableView.h file, UITableView doesn't seem to set itself as a UISCrollViewDelegate so I'm wondering how it manages this (I'm assuming as it recycles cells it must track their position relative to the visible bounds).

I'm pretty new to this platform so I may be missing something obvious. Any help appreciated.

like image 568
Mike Stead Avatar asked Apr 05 '09 18:04

Mike Stead


1 Answers

Found it!! (completely by accident)

I had resigned myself to assign my UIScrollView subclass as a delegate to super then implement the scrollViewDidScroll: delegate method, however part way through implementing I got an exception in the middle of my scrollViewDidScroll method.. One quick look at the stack trace showed me that my delegate method was actually being called from the setContentOffset:

It turns out, if you override setContentOffset: you get a call every time the scroll view moves! and it comes with a handy contentOffset struct to tell you where the scroll view currently is :)

- (void)setContentOffset:(CGPoint)contentOffset
{
    [super setContentOffset:contentOffset];

    NSLog(@"ViewDidScroll: %f, %f", contentOffset.x, contentOffset.y);
}
like image 95
Jo-el Avatar answered Sep 21 '22 11:09

Jo-el