6
votes

Good morning,

I've creates a Subclass of UIScrollView and I now want to know when the user is scrolling in my subclass. For that I implemented it like the following:

ImageScroller.h

@interface UIImageScroller : UIScrollView <UIScrollViewDelegate> {

ImageScroller.m (within the @implementation)

- (void)scrollViewDidScroll:(UIScrollView *)scrollView {

    NSLog(@"did scroll");
}

The problem is, that the method scrollViewDidScroll doesn't seem to get fired. Is there any possibility to get it to work?

I also tried to set the delegate to it self, but it doesn't work.

 - (id)initWithCoder:(NSCoder *)aDecoder {
    if ((self = [super initWithCoder:aDecoder])) {
        self.directionalLockEnabled = YES;
        [self setDelegate:self];
    }
    return self;
}

I added a ScrollView to my XIB-File and set the Class if it to my ImageScroller. Also I've set the Fileowner and I'm using the UIScrollViewDelegate in the .h-File of the ViewController as well as implementing the Method scrollViewDidScroll in the .m-file.

When I set the delegate of my ImageScroller in the code of the .m-file from the XIB like [imageScroller setDelegate:imageScroller] the scrollViewDidScroll is fired in my ImageScroller-Subclass, but the one in my ViewController isn't fired, but I need both.

Any solutions for that?

Thanks for your answers in advance.

3

3 Answers

4
votes

I think you can try setting self.delegate = self; to receive events.

14
votes

I ran into the same problem creating a subclass of the UIScrollView but solved it this way. As mentioned above, you can set yourself (subclass instance) as the delegate however this is what I did.

In the sub class I overrode the following methods

//Override this to detect when the user is scrolling, this is also triggered during view
//layout.  Here you can check your deceleration rate and determine when the scrolling has
//grinded to a halt.
-(void)setContentOffset:(CGPoint)contentOffset

//Override this to detect when the view has been resized (just a handy override)
-(void)setFrame:(CGRect)frame;

As far as the other UIScrollViewDelegate methods, the View Controller should be responsible for handling those in my opinion.

3
votes

If anyone is looking for a Swift answer, it's as simple as this:

override var contentOffset: CGPoint {
    didSet {
        if contentOffset != oldValue {
            //same as scrollViewDidScroll
        }
    }
}