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

前端 未结 5 461
不知归路
不知归路 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:12

    Take advantage of the recursive nature of -viewWithTag:

    - (UIView *)viewWithTagNotCountingSelf:(NSInteger)tag
    {
        UIView *toReturn = nil;
    
        for (UIView *subView in self.subviews) {
            toReturn = [subView viewWithTag:tag];
    
            if (toReturn) {
                break;
            }
        }
        return toReturn;
    }
    

    Edit: this will drill down farther than "grand-subviews": it will get any view within the hierarchy that is not self. Also this is to be implemented in a category on UIView.

提交回复
热议问题