Subview 的事件回應
在 view 的層級中,預設情況下 subview 可以顯示到其父 view 的 frame 區域以外;透過把 clipsToBounds 屬性設為 YES,可以限制 subview 的顯示區域。但 touch 在各個 UIView 之間傳遞時,其區域是被限制在 view 的 frame 內的。這裡包含兩個資訊:1、在目前 view 的 frame 以外所做的操作不會傳遞到該 view;2、如果 touch 事件發生在目前 view 的 frame 以外,該 view 所有的 subview 也不會再收到該訊息。第二點常被忽略,很多奇怪的問題就是這樣引起的。
請看下面這個小例子,自訂 view 的程式碼如下:
SvTestClipSubviewEvent.h
#import <UIKit/UIKit.h> // 預設情況下,subView 可以超出父 view 的 frame,顯示到父 View 外邊 // 但訊息的接收卻受限於父 View 的大小,出了父 View 的 subView 將收不到訊息 @interface SvTestClipSubviewEvent : UIView @end
SvTestClipSubviewEvent.m
#import "SvTestClipSubviewEvent.h"
@interface SvTestClipSubviewEvent ()
- (void)btnAction:(UIButton *)btn;
@end
@implementation SvTestClipSubviewEvent
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
self.backgroundColor = [UIColor redColor];
// 一個位於父 view 範圍之外的按鈕
UIButton *testOutBtn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
testOutBtn.frame = CGRectMake(-80, -50, 70, 30);
[testOutBtn addTarget:self action:@selector(btnAction:) forControlEvents:UIControlEventTouchUpInside];
[testOutBtn setTitle:@"I'm out" forState:UIControlStateNormal];
[self addSubview:testOutBtn];
// 一個位於父 view 範圍之內的按鈕
UIButton *testInBtn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
testInBtn.frame = CGRectMake(20, 30, 70, 30);
[testInBtn setTitle:@"I'm in" forState:UIControlStateNormal];
[testInBtn addTarget:self action:@selector(btnAction:) forControlEvents:UIControlEventTouchUpInside];
[self addSubview:testInBtn];
}
return self;
}
- (void)btnAction:(UIButton *)sender
{
NSLog(@"HI, you tap button %@", [sender titleForState:UIControlStateNormal]);
}
@end
在 ViewController 中加入測試程式碼:
SvTestClipSubviewEvent *testClipSubView = [[SvTestClipSubviewEvent alloc] initWithFrame:CGRectMake(100, 100, 150, 150)]; [self.view addSubview:testClipSubView];
執行後可看到如下介面:

取得 subview
通常在 view 層級中對 subView 的操作有兩種方式:1、保留一個 subview 的引用,之後透過該引用對它操作,但要注意在適當位置加上記憶體維護的程式碼、退出前手動釋放;2、設定 subview 的 Tag,需要時透過 viewWithTag 取得,這種方法較簡潔,也不必自行維護記憶體。
需要注意的是,viewWithTag: 採用深度優先遍歷的演算法,會回傳第一個 tag 與指定 Tag 相等的 subview。這就導致:當一個 view 的多個 subview 的 tag 相同時,我們透過該方法取得的 view 可能並非自己想要的。
下面透過一個小例子驗證。例子中的每個 subview 都是一個設定了對應內容的 UILabel。按鈕回應函式的思路是:先隱藏所有型別為 UILabel 的 subview(排除 UIButton,因為 button 需一直顯示),再依指定的 Tag 取得相應的 subview,並把該 subview 及其 superView 的 hidden 設為 NO,如此即可保證點擊按鈕時只顯示第一個 tag 與指定 tag 相等的 subview。

驗證 viewWithTag 的原理:
首先在 subview1 中添加了兩個 tag 都為 11 的 subview11 與 subview12。執行時,點擊「Show Tag 11」按鈕,螢幕上顯示的是「SubView11」而非「SubView12」,而且不管點擊幾次都只顯示「SubView11」。由此可見,同一層級中查找 subview 的順序遵循 index 由小到大的原則,即位於相對下層者會先被找到。
其次,在 subview1 中添加了 tag 均為 13 的 subview13,同時向 view 中加入 tag 也為 13 的 subview2。執行時點擊「Show Tag 13」,螢幕顯示的是「SubView13」而非「SubView2」。這驗證了 viewWithTag 在搜尋時遵循深度優先遍歷的原則,即會先查找最下層的 view 並遞歸查詢其 subview。
綜合以上兩點可見,viewWithTag 取得 subview 的基本原則是:深度優先、下層優先。