您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 訊息 >> iOS 相關資訊

UITableView 取得 cell 的 row 值:解決自訂儲存格內按鈕拿不到 indexPath

編輯:iOS 相關資訊

在自訂儲存格時常會遇到這樣的需求:cell 裡放了一顆 UIButton,點下去想知道究竟點的是第幾列。如果 cell 的按下事件由 tableView 的 didSelectRowAtIndexPath: 處理,這件事很簡單;但若事件是綁在按鈕自己的 action 上,indexPath 就得另外想辦法取得。

情況一:用程式碼直接對 cell 加入控制項

如果你是透過程式把 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 就是列號。

情況二:以 .xib 建立自訂儲存格

若你是另開一個繼承 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 的階層改了,程式就會悄悄出錯。實務上有幾種更可靠的方式:

  • 在自訂 cell 類別中宣告一個 NSIndexPath *indexPath 屬性,於 cellForRowAtIndexPath: 中順手指派,按鈕 action 直接讀取即可。
  • 用 convertRect: 搭配 rectForRowAtIndexPath: 反推,或直接以座標比對 indexPathForRowAtPoint:。
  • 把按鈕的 tag 設為列號,在 action 中從 sender 讀 tag。

其中第一種最直觀,也最不受 Apple 內部實作變動影響。

  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved