在自訂儲存格時常會遇到這樣的需求:cell 裡放了一顆 UIButton,點下去想知道究竟點的是第幾列。如果 cell 的按下事件由 tableView 的 didSelectRowAtIndexPath: 處理,這件事很簡單;但若事件是綁在按鈕自己的 action 上,indexPath 就得另外想辦法取得。
如果你是透過程式把 UILabel、UIButton 等元件加進 cell,那麼按鈕的 superview 就是 cell 本身,可以這樣取得:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
// 自訂程式碼
return cell;
}
UITableViewCell *cell = (UITableViewCell *)[btn superview]; NSIndexPath *indexPath = [_myTableView indexPathForCell:cell]; NSLog(@"indexPath is = %i", indexPath.row);
其中 btn 是透過程式加到 cell 上的按鈕,_myTableView 是表視圖的實例變數。核心方法是 indexPathForCell:,它會回傳該 cell 對應的 indexPath,再取 row 就是列號。
若你是另開一個繼承 UITableViewCell 的 xib(例如 shopCell.xib)再塞進原本的表視圖,那麼上述寫法就拿不到正確的 row——因為此時按鈕的 superview 鏈條多了一層。
程式碼幾乎一樣,只要多爬兩層即可:
UITableViewCell *cell = (UITableViewCell *)[[[btn superview] superview] superview]; NSIndexPath *indexPath = [_myTableView indexPathForCell:cell]; NSLog(@"indexPath is = %i", indexPath.row);
這裡的三層 superview 分別是:第一層是 shopCell 的 contentView,第二層是 shopCell 這個自訂 cell 本身,第三層才是 UITableView 直接持有的 cell。這三個東西名字相近,很容易搞混,記住順序就不會出錯。
靠 superview 層數硬寫數字其實很脆弱:一旦 Apple 調整了 cell 的內部結構,或你把 xib 的階層改了,程式就會悄悄出錯。實務上有幾種更可靠的方式:
NSIndexPath *indexPath 屬性,於 cellForRowAtIndexPath: 中順手指派,按鈕 action 直接讀取即可。convertRect: 搭配 rectForRowAtIndexPath: 反推,或直接以座標比對 indexPathForRowAtPoint:。其中第一種最直觀,也最不受 Apple 內部實作變動影響。