【问题标题】:Cocoa: Loop through all controls in a window?Cocoa:循环遍历窗口中的所有控件?
【发布时间】:2012-02-10 10:20:32
【问题描述】:

我正在使用 Cocoa 编写 Mac 应用程序。

如何循环/枚举 NSWindow 中的所有按钮、标签和其他 GUI 控件?我想获取每个控件的标签

谢谢!

【问题讨论】:

    标签: macos cocoa user-interface controls


    【解决方案1】:

    我猜你会想要这样的东西:

    - (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];
    

    视图可以有子视图,所以它最终是一个树行走。在这段代码中,我只是使用了简单的递归来实现这一点。

    【讨论】:

    • 嗨,Tommy,谢谢,您的解决方案看起来不错。当我在 NSWindow 的 contentView 上尝试时,它的子视图实际上是空的,我无法访问它上面的 NSButton。你会帮忙吗?谢谢
    • 这真的很奇怪。如果您对 contentView 进行 NSLog 记录,您会得到合适的东西吗?
    • 输出是
    • 打勾表示您解决了问题吗?否则我打算明天做一个小测试,试图弄清楚会发生什么。
    • Tommy,递归解决方案有效。最后,受您的解决方案的启发,我写了一个非递归算法,并将所有 NSView 放入一个 NSMutableArray 中,然后遍历每个控件并确定其类。谢谢
    猜你喜欢
    • 1970-01-01
    • 2013-07-20
    • 1970-01-01
    • 2018-04-17
    • 1970-01-01
    • 1970-01-01
    • 2010-12-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多