NSView 子视图和类型
我有几个自定义 NSBox 子类,称为 OuterBox 和 InnerBox。我已经在 XIB 中设置了我的视图,并像这样安排了层次结构:
OuterBox : NSBox
NSButton
NSBox
InnerBox : NSBox
...and some other views
这个想法是,当 NSButton 被按下时,在 IBAction 方法中,我想获取按钮的超级视图,然后从中获取 InnerBox它与按钮位于同一个 OuterBox 中。
为此,我循环遍历 OuterBox 的子视图并检查它们的类型:
for (NSObject *subview in [outerBox subviews]) {
// this never evaluates to true...
if ([subview isKindOfClass:[InnerBox class]]) {
// ...
}
}
问题是我的 if
语句从未命中。 subview
在调试器中显示为 NSView。根据文档,isKindOfClass:
<块引用>如果接收者是aClass的实例或继承自aClass的任何类的实例,则返回
YES
,否则返回NO
。
我明白为什么它返回 NO
:因为 InnerBox 是 NSView 的一种类型,但反之则不然。但我不知道为什么 subview
是一个 UIView,而它应该是一个 InnerBox。
我已导入 InnerBox.h 并确保 InnerBox 确实是 XIB 中的 InnerBox。我不知道什么可能导致其类型发生变化,或者报告不正确......
I have a couple of custom NSBox subclasses called OuterBox and InnerBox. I've set up my view in a XIB and arranged the hierarchy like this:
OuterBox : NSBox
NSButton
NSBox
InnerBox : NSBox
...and some other views
The idea is that when the NSButton gets pressed, in an IBAction method, I want to get the superview of the button and then, from that, get the InnerBox that is in the same OuterBox as the button.
To do this, I loop through the OuterBox's subviews and check their type:
for (NSObject *subview in [outerBox subviews]) {
// this never evaluates to true...
if ([subview isKindOfClass:[InnerBox class]]) {
// ...
}
}
The problem is that my if
statement never hits. subview
shows up in the debugger as an NSView. According to the documentation, isKindOfClass:
returns
YES
if the receiver is an instance of aClass or an instance of any class that inherits from aClass, otherwiseNO
.
I understand why it's returning NO
: because InnerBox is a type of NSView but not vice versa. But I don't know why subview
is a UIView when it should be an InnerBox.
I have imported InnerBox.h and made sure that the InnerBox really is an InnerBox in the XIB. I don't know what could be causing its type to get changed, or be reported incorrectly...
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
据我所知,当遇到您的
InnerBox
时,isKindOfClass:
应该返回YES
。也许视图没有按照您预期的方式嵌套。需要检查两件事:NSButton
的超级视图是否确实存在OuterBox
? (您可以在按钮的操作方法中NSLog
发送者的超级视图。)InnerBox
确实是外箱
? (也许为InnerBox
设置一个IBOutlet
并为其超级视图设置NSLog
。)As far as I can tell,
isKindOfClass:
should returnYES
when it encounters yourInnerBox
. Perhaps the views aren't nested the way you intended. Two things to check:NSButton
trulythe
OuterBox
? (You couldNSLog
the superview of the sender in your button's action method.)InnerBox
truly a subview of theOuterBox
? (Perhaps set up anIBOutlet
to theInnerBox
andNSLog
its superview.)