How do I properly observe the contentOffset property of my scrollView subclass?

dugla picture dugla · Jan 4, 2012 · Viewed 8k times · Source

In my iOS app I am observing changes to the contentOffset property of my scrollView subclass. My observer handler looks like this:

- (void)observeContentOffsetHandler:(id)aContentOffset {

    NSLog(@"%@", aContentOffset);

}

I chose the parameter to the method arbitrarily as an id for simplicity.

My NSLog'ging looks like this:

-[MyScrollView observeContentOffsetHandler:] [Line 111] NSPoint: {296, 375}
-[MyScrollView observeContentOffsetHandler:] [Line 111] NSPoint: {296, 389}
-[MyScrollView observeContentOffsetHandler:] [Line 111] NSPoint: {295, 401}
-[MyScrollView observeContentOffsetHandler:] [Line 111] NSPoint: {291, 415}

I need to use the x and y values but I have no idea how to get at them. I've tried casting the id to a CGPoint, nope. I've tried changing the param to a CGPoint, nope.

UPDATE

It gets deeper. @mgold no joy. Here is how I set up observation:

self.contentOffsetObserver = [[[Observer alloc] initWithTarget:self action:@selector(observeContentOffsetHandler:)] autorelease];
[self.myScrollViewSubclass addObserver:self.contentOffsetObserver forKeyPath:@"contentOffset" options:NSKeyValueObservingOptionNew context:NULL];

Observer is a handy class I use to make observation easy. Note the observer callback observeContentOffsetHandler:. When I change the signature of this method from its current:

- (void)observeContentOffsetHandler:(id)aContentOffset

to @mgold's suggestion of CGPoint:

- (void)observeContentOffsetHandler:(CGPoint)aContentOffset

It is incorrect as NSLog shows with all zeros for aContentOffset:

-[MyScrollController observeContentOffsetHandler:] [Line 74] aContentOffset 0 0
-[MyScrollController observeContentOffsetHandler:] [Line 74] aContentOffset 0 0
-[MyScrollController observeContentOffsetHandler:] [Line 74] aContentOffset 0 0
-[MyScrollController observeContentOffsetHandler:] [Line 74] aContentOffset 0 0

Not sure what my move here is.

Answer

dugla picture dugla · Jan 5, 2012

Got it. The method correct signature is:

- (void)observeContentOffsetHandler:(NSValue *)aContentOffset

Retrieval of the CGPoint is then trivial:

CGPoint pt = [aContentOffset CGPointValue];

Cheers,
Doug