使用 UITableView 時,很常需要客製化 cell,例如在裡面放 button 與 label 來實作「加入收藏」「播放」這類操作。問題是:按下 button 之後,往往還需要知道這個 button 所在 cell 中 label 存的值。
一般做法是用 tag 標記。但當 table 有很多列、而且 cell 會被重用時,設定 tag 變得很麻煩也容易出錯。這裡介紹另一種思路。
iOS 裡每個視圖都有父視圖(superview),那能不能靠這個特性找到 cell?經過測試,答案是可行的。
先給 button 寫一個測試用的方法:
- (void)btn_Onclick:(id)sender
{
UIButton *btn = (UIButton *)sender;
NSLog(@" [btn superview] = %@ ", [[btn superview] class]);
NSLog(@" [[[btn superview] superview] class] = %@",
[[[btn superview] superview] class]);
}
輸出結果:
2014-09-10 19:09:42.203 superview[4720:60b] [btn superview] = UITableViewCellScrollView 2014-09-10 19:09:42.646 superview[4720:60b] [[[btn superview] superview] class] = UITableViewCell
看來沒問題:button 的父視圖是 UITableViewCellScrollView,再往上一層就是 UITableViewCell。
然而測試發現,對於繼承自 UITableViewCell 的自訂類別(本例為 SongTableViewCell),層級會多一層,需要再往上找一次:
NSLog(@" [btn superview] = %@ ", [[btn superview] class]);
NSLog(@" [[[btn superview] superview] class] = %@",
[[[btn superview] superview] class]);
NSLog(@" [[[[btn superview] superview] superview] class] = %@",
[[[[btn superview] superview] superview] class]);
輸出:
2014-09-10 18:54:50.036 Music_Player[4451:60b] [btn superview] = UITableViewCellContentView 2014-09-10 18:54:50.036 Music_Player[4451:60b] [[[btn superview] superview] class] = UITableViewCellScrollView 2014-09-10 18:54:50.036 Music_Player[4451:60b] [[[[btn superview] superview] superview] class] = SongTableViewCell
原因很清楚:自訂 cell 通常會把控制項放在 contentView 裡(本例是 UITableViewCellContentView),因此比預設結構多一層。
順帶一提,viewWithTag: 有個隱藏行為:它無法找到 tag 為 0 的元件。即使你確實把某個 button 的 tag 設為 0 也找不到,推測是與系統預設的 tag 值重複有關。實務上要避開 0,從 1 開始編號。
靠 superview 鏈硬找層級很脆弱:只要 Apple 改了 cell 的內部結構,或你自己多包一層容器,程式碼就失效,而且這種錯誤只會在執行期爆發。
更穩健的兩個方案:
方案一:用座標反查 indexPath。 完全不依賴視圖階層:
- (void)buttonClicked:(UIButton *)sender
{
CGPoint point = [sender convertPoint:CGPointZero toView:self.tableView];
NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:point];
NSInteger row = indexPath.row;
// 用 row 取出對應資料
}
方案二:在 cell 上宣告回呼 block。 這是最推薦的現代做法,讓 cell 自己決定要告訴外界什麼,而不是讓外界去猜 cell 的結構:
// 在自訂 cell 中
@property (nonatomic, copy) void (^didTapButton)(NSInteger index);
// cellForRowAtIndexPath 中設定
cell.didTapButton = ^(NSInteger index) {
// 處理點擊,index 由 cell 內部提供
};
另外,若 cell 有對應的 model 物件,直接在 cell 上存一份 model 引用,點擊時讀 cell.model 即可,完全不需要反查層級。