2014-10-22 40 views
0

我在故事板中放置了一個tableview,並用一個「0」作爲標記的按鈕填充單元格。我使用數組填充tableview。讓我們說我的數組中有20個元素,這使得它在桌面視圖上有20個單元格。這是我用來給每個單元格上的按鈕添加標籤的代碼。表視圖中的按鈕標記重置?

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { 
    if (tableView == _tblCart) { 
     static NSString *cellIdentifier = @"CartCell"; 
     UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier]; 
     cell.selectionStyle = UITableViewCellSelectionStyleGray; 

     UIButton *btn = (UIButton *)[cell viewWithTag:0]; 
     [btn setTag:indexPath.row]; 
     [btn addTarget:self action:@selector(logTag:) forControlEvents:UIControlEventTouchUpInside]; 

     return cell; 
    } 
    return nil; 
} 

我以爲我的代碼可以正常工作,但實際上有些問題。在單元格0-5上,按鈕標籤是正確的。在下面的單元格中,標籤將重置爲0.我做錯了什麼?

+0

你的做法是不正確的,不需要設置按鈕標記爲細胞指數 – 2014-10-22 10:26:56

回答

1

這裏還有另外一個邏輯問題,你正在重複使用表格單元格,其中一些已經將按鈕的標籤更改爲0以外的東西。所以,如果你得到一個重用的表格單元格,會有一段時間UIButton將不會有零標籤,因此您將無法正確更改它。

+0

我完全忘了可重複使用的thingie。謝了哥們! :) – 2014-10-22 10:44:41

1

請勿將0作爲標記標識符設置爲視圖。
所有的UIViews默認都有一個標籤0.

所以 [cell viewWithTag:0];
可能會返回細胞的contentView

0

Flexicoder和l0gg3r都是正確的。另外,依靠按鈕的標籤作爲行標識符在我看來是一種笨重的解決方法。考慮這樣的方法:

- (void)logTag:(UIButton *)sender { 
    NSIndexPath *indexPath = [_tblCart indexPathForRowAtPoint:[_tblCart convertPoint:sender.center fromView:sender]]; 
    // do your stuff knowing which indexPath the button belongs to 
}