天天看点

viewWithTag方法的一些问题

以前马虎,一直以为viewWithTag方法只去遍历subviews,直到我遇到了一个大坑之后,才去查苹果文档,发现这个方法不仅遍历subviews,也遍历这个view的本身。
           

下面是我遇到的坑:

UIView *view=[UIView new];
view.tag=3;
UILabel *label=[UILable new];
label.tag=3;
[view addSubView:label];
UIView *result=[view viewWithTag:3];
           

得到的result竟然是view本身,而不是label。

查过文档,发现有这么一句:

Discussion

This method searches the current view and all of its subviews for the specified view.

且遍历的时候,优先搜索view本身,再去搜索子view,稍不注意就会酿下大错。

所以以后,子view上的tag,数值应该设置比父view的tag大,以免马大哈出现诡异的问题。

UIView *view=[UIView new];
view.tag=3;
UILabel *label=[UILable new];
lable.tag=3+1000;
[view addSubView:label];
UILabel *result=[view viewWithTag:3+1000];