views:

95

answers:

2

How do I determine what the view structure on my iPhone program while running on the simulator?

+2  A: 

Hi, you can use some algo like this:

-(void)inspectView:(UIView *)aView level:(NSString *)level {
    NSLog(@"Level:%@", level);
    NSLog(@"View:%@", aView);

    NSArray *arr = [aView subviews];
    for (int i=0;i<[arr count];i++) {
        [self inspectView:[arr objectAtIndex:i]
          level:[NSString stringWithFormat:@"%@/%d", level, i]];
    }
}

And add this line in an viewDidLoad for example:

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    [self inspectView:self.viewControllers level:@""];
}

source: view hierarchy

Yannick L.
+1  A: 

Along the lines of what Yannick suggests, Erica Sadun has code here that pretty-prints the view hierarchy (with class and frame information). You can make this into a UIView category with the following interface:

#import <UIKit/UIKit.h>

@interface UIView (ExploreViews)

- (void)exploreViewAtLevel:(int)level;

@end

and implementation:

#import "UIView+ExploreViews.h"

void doLog(int level, id formatstring,...)
{
    int i;
    for (i = 0; i < level; i++) printf("    ");

    va_list arglist;
    if (formatstring)
    {
        va_start(arglist, formatstring);
        id outstring = [[NSString alloc] initWithFormat:formatstring arguments:arglist];
        fprintf(stderr, "%s\n", [outstring UTF8String]);
        va_end(arglist);
    }
}

@implementation UIView (ExploreViews)

- (void)exploreViewAtLevel:(int)level;
{
    doLog(level, @"%@", [[self class] description]);
    doLog(level, @"%@", NSStringFromCGRect([self frame]));
    for (UIView *subview in [self subviews])
        [subview exploreViewAtLevel:(level + 1)];
}

@end
Brad Larson
This solution does what I asked for. The fun part is always trying to ask the right question.
Chris