我正在用Cocoa编程Mac应用程序。
如何循环/枚举NSWindow中的所有按钮、标签和其他GUI控件?我想得到每个控制的标签
谢谢!
我想你会想要这样的东西:
- (void)addLabelsFromSubviewsOf:(NSView *)view to:(NSMutableArray *)array
{
// get the label from this view, if it has one;
// I'm unsure what test you want here, maybe:
if([view respondsToSelector:@selector(stringValue)])
[array addObject:[view stringValue]];
// or possibly:
// if([view isKindOfClass:[NSTextField class]]) ?
// and traverse all subviews
for(NSView *view in [view subviews])
{
[self addLabelsFromSubviewsOf:view to:array];
}
}
...
NSMutableArray *array = [NSMutableArray array];
[self addLabelsFromSubviewsOf:[window contentView] to:array];
视图可以有子视图,所以它最终会变成一个树行。在这段代码中,我只是使用了简单的递归来实现这一点。