On iOS, is there a way to search ONLY subviews with a certain tag?

前端 未结 5 471
不知归路
不知归路 2021-01-21 16:55

Because right now, viewWithTag actually search for itself first, and then all subviews recursively down the whole subtree, for a view with that tag.

But wha

5条回答
  •  广开言路
    2021-01-21 17:10

    For 1 level:

    UIView *view;
    for (int i = 0; i < viewToSearch.subviews.count; i++){
        UIView *subview = viewToSearch.subviews[i];
        if (subview.tag == tagToSeach){
            view = subview;
            break;
        }
    }
    

    To search a view hierarchy with multiple levels:

    __block UIView *view;
    BOOL (^__block searchViewForTag)(UIView *,NSInteger) = ^(UIView *aView, NSInteger tag){
        for (UIView *subview in aView.subviews){
            if (subview.tag == tag){
                view = subview;
                return YES;
            }
            if (searchViewForTag(subview,tag)) return YES;
        }
        return NO;
    };
    NSInteger tagToSearchFor = 1;
    searchViewForTag(viewToSearch,tagToSearchFor);
    
    //Do something with view
    

提交回复
热议问题