如何在Cocoa中打印控件层次结构?

eri*_*icg 22 macos cocoa

Carbon有一个名为DebugPrintControlHierarchy的有用函数.

NSView或NSWindow有类似的东西吗?

kpe*_*yua 44

我不知道究竟DebugPrintControlHierarchy打印了什么,但NSView有一个有用的方法调用_subtreeDescription,它返回一个字符串,描述接收器下面的整个层次结构,包括类,框架和其他有用的信息.

不要害怕领先的_下划线.它不是公共API,但它在gdb中被公开使用.您可以在AppKit发行说明中看到它以及一些示例输出.


Jos*_*zzi 5

这是我后来构建的NSView类别的内容:

+ (NSString *)hierarchicalDescriptionOfView:(NSView *)view 
                                      level:(NSUInteger)level
{

  // Ready the description string for this level
  NSMutableString * builtHierarchicalString = [NSMutableString string];

  // Build the tab string for the current level's indentation
  NSMutableString * tabString = [NSMutableString string];
  for (NSUInteger i = 0; i <= level; i++)
    [tabString appendString:@"\t"];

  // Get the view's title string if it has one
  NSString * titleString = ([view respondsToSelector:@selector(title)]) ? [NSString stringWithFormat:@"%@", [NSString stringWithFormat:@"\"%@\" ", [(NSButton *)view title]]] : @"";

  // Append our own description at this level
  [builtHierarchicalString appendFormat:@"\n%@<%@: %p> %@(%li subviews)", tabString, [view className], view, titleString, [[view subviews] count]];  

  // Recurse for each subview ...
  for (NSView * subview in [view subviews])
    [builtHierarchicalString appendString:[NSView hierarchicalDescriptionOfView:subview 
                                                                          level:(level + 1)]];

  return builtHierarchicalString;
}

- (void)logHierarchy
{
  NSLog(@"%@", [NSView hierarchicalDescriptionOfView:self
                                               level:0]);
}
Run Code Online (Sandbox Code Playgroud)

用法

将其转储到NSView类别中,将其转储到其中.在您想要使用它的任何地方添加类别标题,然后调用[myView logHierarchy];并观察它.