87

如何遍历 UIView 的所有子视图,以及它们的子视图和它们的子视图?

4

18 回答 18

125

使用递归:

// UIView+HierarchyLogging.h
@interface UIView (ViewHierarchyLogging)
- (void)logViewHierarchy;
@end

// UIView+HierarchyLogging.m
@implementation UIView (ViewHierarchyLogging)
- (void)logViewHierarchy
{
    NSLog(@"%@", self);
    for (UIView *subview in self.subviews)
    {
        [subview logViewHierarchy];
    }
}
@end

// In your implementation
[myView logViewHierarchy];
于 2010-04-30T17:41:02.937 回答
36

好吧,这是我对 UIView 类使用递归和包装器(类别/扩展)的解决方案。

// UIView+viewRecursion.h
@interface UIView (viewRecursion)
- (NSMutableArray*) allSubViews;
@end

// UIView+viewRecursion.m
@implementation UIView (viewRecursion)
- (NSMutableArray*)allSubViews
{
   NSMutableArray *arr=[[[NSMutableArray alloc] init] autorelease];
   [arr addObject:self];
   for (UIView *subview in self.subviews)
   {
     [arr addObjectsFromArray:(NSArray*)[subview allSubViews]];
   }
   return arr;
}
@end

用法:现在您应该循环遍历所有子视图并根据需要对其进行操作。

//disable all text fields
for(UIView *v in [self.view allSubViews])
{
     if([v isKindOfClass:[UITextField class]])
     {
         ((UITextField*)v).enabled=NO;
     }
}
于 2010-12-15T06:45:16.147 回答
27

这是另一个 Swift 实现:

extension UIView {
    var allSubviews: [UIView] {
        return self.subviews.flatMap { [$0] + $0.allSubviews }
    }
}
于 2018-06-05T04:57:29.920 回答
16

Swift 3 中的一个解决方案,它提供了所有subviews内容而不包括视图本身:

extension UIView {
var allSubViews : [UIView] {

        var array = [self.subviews].flatMap {$0}

        array.forEach { array.append(contentsOf: $0.allSubViews) }

        return array
    }
}
于 2016-09-20T20:56:13.840 回答
12

刚刚通过调试器找到了一种有趣的方法:

http://idevrecipes.com/2011/02/10/exploring-iphone-view-hierarchies/

引用此 Apple 技术说明:

https://developer.apple.com/library/content/technotes/tn2239/_index.html#SECUIKIT

只需确保您的调试器已暂停(或者手动设置暂停的断点),您就可以请求recursiveDescription.

于 2011-02-18T23:25:02.443 回答
12

我在创建时标记所有内容。然后很容易找到任何子视图。

view = [aView viewWithTag:tag];
于 2011-07-07T16:15:34.767 回答
11

这是一个具有实际视图循环和中断功能的示例。

迅速:

extension UIView {

    func loopViewHierarchy(block: (_ view: UIView, _ stop: inout Bool) -> ()) {
        var stop = false
        block(self, &stop)
        if !stop {
            self.subviews.forEach { $0.loopViewHierarchy(block: block) }
        }
    }

}

调用示例:

mainView.loopViewHierarchy { (view, stop) in
    if view is UIButton {
        /// use the view
        stop = true
    }
}

反向循环:

extension UIView {

    func loopViewHierarchyReversed(block: (_ view: UIView, _ stop: inout Bool) -> ()) {
        for i in stride(from: self.highestViewLevel(view: self), through: 1, by: -1) {
            let stop = self.loopView(view: self, level: i, block: block)
            if stop {
                break
            }
        }
    }

    private func loopView(view: UIView, level: Int, block: (_ view: UIView, _ stop: inout Bool) -> ()) -> Bool {
        if level == 1 {
            var stop = false
            block(view, &stop)
            return stop
        } else if level > 1 {
            for subview in view.subviews.reversed() {
            let stop = self.loopView(view: subview, level: level - 1, block: block)
                if stop {
                    return stop
                }
            }
        }
        return false
    }

    private func highestViewLevel(view: UIView) -> Int {
        var highestLevelForView = 0
        for subview in view.subviews.reversed() {
            let highestLevelForSubview = self.highestViewLevel(view: subview)
            highestLevelForView = max(highestLevelForView, highestLevelForSubview)
        }
        return highestLevelForView + 1
    }
}

调用示例:

mainView.loopViewHierarchyReversed { (view, stop) in
    if view is UIButton {
        /// use the view
        stop = true
    }
}

目标-C:

typedef void(^ViewBlock)(UIView* view, BOOL* stop);

@interface UIView (ViewExtensions)
-(void) loopViewHierarchy:(ViewBlock) block;
@end

@implementation UIView (ViewExtensions)
-(void) loopViewHierarchy:(ViewBlock) block {
    BOOL stop = NO;
    if (block) {
        block(self, &stop);
    }
    if (!stop) {
        for (UIView* subview in self.subviews) {
            [subview loopViewHierarchy:block];
        }
    }
}
@end

调用示例:

[mainView loopViewHierarchy:^(UIView* view, BOOL* stop) {
    if ([view isKindOfClass:[UIButton class]]) {
        /// use the view
        *stop = YES;
    }
}];
于 2014-09-16T19:57:19.743 回答
6

在 Ole Begemann 的帮助下。我添加了几行来将块概念融入其中。

UIView+HierarchyLogging.h

typedef void (^ViewActionBlock_t)(UIView *);
@interface UIView (UIView_HierarchyLogging)
- (void)logViewHierarchy: (ViewActionBlock_t)viewAction;
@end

UIView+HierarchyLogging.m

@implementation UIView (UIView_HierarchyLogging)
- (void)logViewHierarchy: (ViewActionBlock_t)viewAction {
    //view action block - freedom to the caller
    viewAction(self);

    for (UIView *subview in self.subviews) {
        [subview logViewHierarchy:viewAction];
    }
}
@end

在 ViewController 中使用 HierarchyLogging 类别。你现在可以自由地去做你需要做的事情。

void (^ViewActionBlock)(UIView *) = ^(UIView *view) {
    if ([view isKindOfClass:[UIButton class]]) {
        NSLog(@"%@", view);
    }
};
[self.view logViewHierarchy: ViewActionBlock];
于 2011-09-16T09:50:21.197 回答
4

这是一个递归代码:-

 for (UIView *subViews in yourView.subviews) {
    [self removSubviews:subViews];

}   

-(void)removSubviews:(UIView *)subView
{
   if (subView.subviews.count>0) {
     for (UIView *subViews in subView.subviews) {

        [self removSubviews:subViews];
     }
  }
  else
  {
     NSLog(@"%i",subView.subviews.count);
    [subView removeFromSuperview];
  }
}
于 2012-01-20T11:04:42.247 回答
4

无需创建任何新功能。只需在使用 Xcode 进行调试时执行此操作。

在视图控制器中设置断点,并使应用程序在此断点处暂停。

右键单击空白区域,然后在 Xcode 的 Watch 窗口中按“Add Expression...”。

输入这一行:

(NSString*)[self->_view recursiveDescription]

如果该值太长,请右键单击它并选择“打印...的描述”。您将在控制台窗口中看到 self.view 的所有子视图。如果您不想看到 self.view 的子视图,请将 self->_view 更改为其他内容。

完毕!没有gdb!

于 2012-10-24T04:29:18.707 回答
3

顺便说一句,我做了一个开源项目来帮助完成这类任务。这真的很简单,并且使用 Objective-C 2.0 块在层次结构中的所有视图上执行代码。

https://github.com/egold/UIViewRecursion

例子:

-(void)makeAllSubviewsGreen
{
    [self.view runBlockOnAllSubviews:^(UIView *view) {

        view.backgroundColor = [UIColor greenColor];
    }];
}
于 2012-05-03T23:03:36.210 回答
2

这是上面Ole Begemann 答案的变体,它添加了缩进来说明层次结构:

// UIView+HierarchyLogging.h
@interface UIView (ViewHierarchyLogging)
- (void)logViewHierarchy:(NSString *)whiteSpaces;
@end

// UIView+HierarchyLogging.m
@implementation UIView (ViewHierarchyLogging)
- (void)logViewHierarchy:(NSString *)whiteSpaces {
    if (whiteSpaces == nil) {
        whiteSpaces = [NSString string];
    }
    NSLog(@"%@%@", whiteSpaces, self);

    NSString *adjustedWhiteSpaces = [whiteSpaces stringByAppendingFormat:@"    "];

    for (UIView *subview in self.subviews) {
        [subview logViewHierarchy:adjustedWhiteSpaces];
    }
}
@end
于 2013-07-14T08:32:39.283 回答
1

此答案中发布的代码遍历所有窗口和所有视图及其所有子视图。它用于将视图层次结构的打印输出转储到 NSLog,但您可以将其用作任何视图层次结构遍历的基础。它使用递归 C 函数来遍历视图树。

于 2010-05-01T01:06:34.970 回答
0

前段时间我写了一个类别来调试一些视图。

IIRC,发布的代码是有效的。如果没有,它将为您指明正确的方向。使用风险自负等。

于 2010-04-30T17:42:35.477 回答
0

这也显示了层次结构级别

@implementation UIView (ViewHierarchyLogging)
- (void)logViewHierarchy:(int)level
{
    NSLog(@"%d - %@", level, self);
    for (UIView *subview in self.subviews)
    {
        [subview logViewHierarchy:(level+1)];
    }
}
@end
于 2011-11-18T11:14:31.147 回答
0

希望我先找到这个页面,但是如果(出于某种原因)您想以非递归方式执行此操作,而不是在类别中,并且使用更多代码行

于 2012-05-15T21:49:00.687 回答
0

我认为所有使用递归的答案(调试器选项除外)都使用了类别。如果您不需要/想要一个类别,您可以只使用实例方法。例如,如果您需要获取视图层次结构中所有标签的数组,您可以这样做。

@interface MyViewController ()
@property (nonatomic, retain) NSMutableArray* labelsArray;
@end

@implementation MyViewController

- (void)recursiveFindLabelsInView:(UIView*)inView
{
    for (UIView *view in inView.subviews)
    {
        if([view isKindOfClass:[UILabel class]])
           [self.labelsArray addObject: view];
        else
           [self recursiveFindLabelsInView:view];
    }
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];

    self.labelsArray = [[NSMutableArray alloc] init];
    [self recursiveFindLabelsInView:self.view];

    for (UILabel *lbl in self.labelsArray)
    {
        //Do something with labels
    }
}
于 2016-03-03T16:57:39.700 回答
-1

下面的方法创建一个或多个可变数组,然后循环输入视图的子视图。这样做时,它会添加初始子视图,然后查询该子视图是否有任何子视图。如果为真,它会再次调用自己。这样做直到添加了层次结构的所有视图。

-(NSArray *)allSubs:(UIView *)view {

    NSMutableArray * ma = [NSMutableArray new];
    for (UIView * sub in view.subviews){
        [ma addObject:sub];
        if (sub.subviews){
            [ma addObjectsFromArray:[self allSubs:sub]];
        }
    }
    return ma;
}

调用使用:

NSArray * subviews = [self allSubs:someView];
于 2017-01-10T18:00:05.777 回答