viewWithTagメソッドは入れ子になったビューにもアクセスできるみたい

きょうお邪魔したiOS勉強会議 #2にて、
「入れ子になったUIViewも、viewWithTagで親からアクセスできるのか」と疑問が上がったので、その場でためしてみました。
せっかくなのでUP。

UIView* viewA = [[UIView alloc] initWithFrame:self.view.frame];
UIButton* buttonA = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 100, 100)];
[viewA setTag:1];
[buttonA setTag:2];

UIView* viewB = [[UIView alloc] initWithFrame:self.view.frame];
UIButton* buttonB = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 200, 200)];
[viewB setTag:3];
[buttonB setTag:4];

UIView* viewC = [[UIView alloc] initWithFrame:self.view.frame];
UIButton* buttonC = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 300, 300)];
[viewC setTag:5];
[buttonC setTag:6];

// 入れ子にする viewA -> buttonA/viewB -> buttonB/viewC -> buttonC という感じ
[viewC addSubview:buttonC];
[viewB addSubview:buttonB];
[viewB addSubview:viewC];
[viewA addSubview:buttonA];
[viewA addSubview:viewB];

[self.view addSubview:viewA];

NSLog(@"%@", [self.view viewWithTag:0]);
NSLog(@"%@", [self.view viewWithTag:1]);
NSLog(@"%@", [self.view viewWithTag:2]);
NSLog(@"%@", [self.view viewWithTag:3]);
NSLog(@"%@", [self.view viewWithTag:4]);
NSLog(@"%@", [self.view viewWithTag:5]);
NSLog(@"%@", [self.view viewWithTag:6]);

dump結果はこちら。

<UIView: 0x6a227f0; frame = (0 0; 320 460); autoresize = W+H; layer = <CALayer: 0x6a21d90>>

<UIView: 0x6a21bb0; frame = (0 0; 320 460); tag = 1; layer = <CALayer: 0x6a22040>>
<UIButton: 0x6a23870; frame = (0 0; 100 100); opaque = NO; tag = 2; layer = <CALayer: 0x6a23950>>

<UIView: 0x6a23e60; frame = (0 0; 320 460); tag = 3; layer = <CALayer: 0x6a23e90>>
<UIButton: 0x6a23ec0; frame = (0 0; 200 200); opaque = NO; tag = 4; layer = <CALayer: 0x6a23f50>>

<UIView: 0x6a24010; frame = (0 0; 320 460); tag = 5; layer = <CALayer: 0x6a24040>>
<UIButton: 0x6a24070; frame = (0 0; 300 300); opaque = NO; tag = 6; layer = <CALayer: 0x6a24100>>

とれた(*'◡'*)!


tagのデフォルト値は0なので、うっかり[(UIImageView*)[view viewWithTag:0] hogehoge];とかやると、
重複している他のパーツを巻き込んで落ちかねないです。
(setTagしていないself.viewがviewWithTag:0に対応しています)
tagを設定するときは、1以上の整数にするのが望ましいですね。

もしくは、複数のパーツのtagを揃えておいて[ [view viewWithTag:1] setHidden:YES]; とまとめて消したりとかっていう使い道もあるのかも。