【问题标题】:Is there a recursiveDescription method for the view controller hierarchy?视图控制器层次结构是否有 recursiveDescription 方法?
【发布时间】:2013-01-07 10:07:05
【问题描述】:

recursiveDescription 在调试视图层次结构时非常有用。 View controller 层次结构也很重要,有没有等价的?

【问题讨论】:

    标签: objective-c ios uiviewcontroller


    【解决方案1】:

    为了简明扼要,我在 Xcode 的调试器控制台中使用以下命令来打印视图控制器层次结构:

    po [[[UIWindow keyWindow] rootViewController] _printHierarchy]
    

    附:这仅适用于 ios8 及更高版本,仅用于调试目的。

    链接到帮助我发现这个和许多其他出色调试技术的文章的链接是this

    编辑 1: 在 Swift 2 中,您可以通过以下方式打印层次结构:

    UIApplication.sharedApplication().keyWindow?.rootViewController?.valueForKey("_‌​printHierarchy")
    

    编辑 2: 在 Swift 3 中,您可以通过以下方式打印层次结构:

    UIApplication.shared.keyWindow?.rootViewController?.value(forKey: "_printHierarchy")
    

    【讨论】:

    • 在 Swift 中:UIApplication.sharedApplication().keyWindow?.rootViewController?.valueForKey("_printHierarchy")
    • 谢谢。我会将其添加到答案中。
    • 在 Swift 5 中:po UIApplication.shared.keyWindow?.rootViewController?.value(forKey: "_printHierarchy")
    【解决方案2】:

    更新 - 类似的功能现在以 Apple 提供的形式作为 _printHierarchy 方法提供,因此您不再需要此类别。

    现在有:

    Github: Recursive description category for view controllers.

    这向UIViewController 添加了一个recursiveDescription 方法,该方法打印出视图控制器层次结构。非常适合检查您是否正确添加和删除子视图控制器。

    代码很简单,包括这里以及上面的GitHub链接:

    @implementation UIViewController (RecursiveDescription)
    
    -(NSString*)recursiveDescription
    {
        NSMutableString *description = [NSMutableString stringWithFormat:@"\n"];
        [self addDescriptionToString:description indentLevel:0];
        return description;
    }
    
    -(void)addDescriptionToString:(NSMutableString*)string indentLevel:(NSInteger)indentLevel
    {
        NSString *padding = [@"" stringByPaddingToLength:indentLevel withString:@" " startingAtIndex:0];
        [string appendString:padding];
        [string appendFormat:@"%@, %@",[self debugDescription],NSStringFromCGRect(self.view.frame)];
    
        for (UIViewController *childController in self.childViewControllers)
        {
            [string appendFormat:@"\n%@>",padding];
            [childController addDescriptionToString:string indentLevel:indentLevel + 1];
        }
    }
    
    @end
    

    【讨论】:

      【解决方案3】:

      最快的方法(在 lldb/Xcode 调试器中):

      po [UIViewController _printHierarchy]
      

      【讨论】:

        【解决方案4】:

        _printHierarchy 没有为 VC 视图的子视图组件提供递归信息。

        方法一:使用 lldb 命令获取完整的视图层次结构。

        po [[[UIApplication sharedApplication] keyWindow] recursiveDescription]
        

        方法 2: 使用 XCode 调试器中的“Debug View Hierarchy”按钮获取所有信息的最佳方式。

        【讨论】:

        • 呃,这很好,但问题特别提到了 recursiveDescription 并且我正在寻找视图控制器层次结构的等效项。
        猜你喜欢
        • 2021-07-10
        • 1970-01-01
        • 2012-10-16
        • 2010-12-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多