0

我正在尝试计算 UIScrollView 中子视图的总高度:

[self.subviews valueForKeyPath:@"bounds.size.@sum.height"];

但这会引发以下内容:

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

我尝试将@sum操作员放置在该路径中的各个位置,结果都相同。

当然我可以用循环来做到这一点,但我对 KVC 解决方案特别好奇——我认为这是可能的,我只是做错了。什么是正确的路径?

4

2 回答 2

3

这不可能。sizeCGRect结构中的一个属性,而不是某个类的某个属性(对于 的产量相同height)。您不能使用 KVC 检索这些值,因为bounds它不是一个对象,只是一个结构。

于 2010-09-18T18:37:11.047 回答
3

您可以这样做,但不能直接这样做(有关原因,请参阅@JoostK 的答案)。这是我的做法:

创建一个UIView添加方法的类别,如下所示:

@interface UIView (KVCAdditions)

- (CGFloat) boundsHeight;

@end

@implementation UIView (KVCAdditions)

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

@end

现在你应该能够做到这一点:

NSNumber * totalHeight = [[self subviews] valueForKeyPath:@"@sum.boundsHeight"];
于 2010-09-18T19:59:28.027 回答