天天看點

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];