用于求和 UIView 子视图属性的 KVC 路径是什么?

发布于 2024-09-24 04:02:50 字数 576 浏览 1 评论 0原文

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

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

但这会引发以下问题:

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

我尝试将 @sum 运算符放置在该路径中的各个位置,所有结果都相同。

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

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

辞别 2024-10-01 04:02:50

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

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.

花开半夏魅人心 2024-10-01 04:02:50

你可以这样做,但不能直接这样做(请参阅@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"];

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"];
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文