views:

49

answers:

2

I'm trying to calculate the total height of subviews in a UIScrollView:

[self.subviews valueForKeyPath:@"[email protected]"];

But that throws the following:

'NSUnknownKeyException', reason: '[<NSConcreteValue 0x4b10170> valueForUndefinedKey:]: this class is not key value coding-compliant for the key size.'

I've tried placing the @sum operator in various places in that path, all with the same result.

Of course I could just do this with a loop, but I'm specifically curious about the KVC solution -- I assume it's possible and I'm just doing it wrong. What's the proper path?

+2  A: 

It is not possible. size is a property in the CGRect struct, not some property of some class (same yields for height). You can't retrieve these values using KVC, since bounds is not an object, just a struct.

JoostK
That explains it. Thanks!
Josh French
+1  A: 

You can do it, but not directly (See @JoostK's answer for why). Here's how I would do it:

Create a UIView category that adds a method, like this:

@interface UIView (KVCAdditions)

- (CGFloat) boundsHeight;

@end

@implementation UIView (KVCAdditions)

- (CGFloat) boundsHeight {
  return [self bounds].size.height;
}

@end

Now you should be able to do this:

NSNumber * totalHeight = [[self subviews] valueForKeyPath:@"@sum.boundsHeight"];
Dave DeLong
Smart way to do it, but not the method of my choice. Adding a method just to be able to use KVC for a simple summation does not make sense for me. Neat illustration of the possibility though.
JoostK