2011-03-01 170 views
1

我有一個自定義UITableViewCell有幾個按鈕。當代碼被全部下一個視圖控制器,我的按鈕被聲明如下:自定義UITableViewCell UIButton

myButton = [UIButton buttonWithType:UIButtonTypeRoundedRect]; 
[myButton addTarget:self 
      action:@selector(myButtonAction:) 
    forControlEvents:UIControlEventTouchUpInside]; 
[myButton setTitle:@"Action" forState:UIControlStateNormal]; 
myButton.frame = CGRectMake(20, 80, 72, 37); 
[self addSubview:myButton]; 

昨晚我子類的UITableViewCell,所以代碼變成這樣:

myButton = [UIButton buttonWithType:UIButtonTypeRoundedRect]; 
[myButton addTarget:viewController 
      action:@selector(myButtonAction:) 
    forControlEvents:UIControlEventTouchUpInside]; 
[myButton setTitle:@"Action" forState:UIControlStateNormal]; 
myButton.frame = CGRectMake(20, 80, 72, 37); 
[self addSubview:damageButton]; 

因爲這樣做,但是,推任何單元格上的按鈕都會導致該操作僅影響表格中的第一行,我不知道爲什麼。

行動代碼:

UIButton *button = (UIButton *)sender; 
UIView *contentView = [button superview]; 
UITableViewCell *cell = (UITableViewCell *)[contentView superview]; 
NSIndexPath *indexPath = [[self tableView] indexPathForCell:cell]; 

//do something with objectAtIndex:indexPath.row 

我知道這是常見設置標籤物業indexPath.row在表視圖使用的UIButton。但是,我在數據源中使用兩個單獨的數組來填充TableView的兩個不同部分,所以我認爲這不會起作用。

+0

也許它只是我,但按鈕的代碼看起來完全一樣。 – 2011-03-01 13:03:15

+0

也許你的代碼並不是真的那樣,但你並沒有添加你創建的同一個按鈕(myButton vs damageButton)。 – jv42 2011-03-01 13:24:31

+0

@fluchtpunkt - 唯一的區別是目標是一個視圖控制器,我作爲一個屬性傳遞 – DVG 2011-03-01 14:23:32

回答

6

的問題,在端部,是,我是添加子視圖的單元對象,而不是內容查看的細胞對象。我改變了這個按鈕代碼,它被解決了:

UIButton *button = (UIButton *)sender; 
UITableViewCell *cell = (UITableViewCell *)[button superview]; 
NSIndexPath *indexPath = [[self tableView] indexPathForCell:cell]; 
-1

不要繼承UITableViewCell(或UITableView),它通常是不必要的,可能會導致問題。表單元格有一個contentView這是一個定製的好地方。

推薦閱讀:

http://cocoawithlove.com/2009/04/easy-custom-uitableview-drawing.html

然後:

http://cocoawithlove.com/2010/12/uitableview-construction-drawing-and.html

+0

嗯。我是UITableViewCell的子類來處理我遇到的滾動性能問題。也許有更好的辦法。 – DVG 2011-03-01 14:26:56

+2

我總是繼承UITableViewCell以避免在ViewControllers中放置大量表示代碼,而是將其放置在獨立的單元類中。 – jv42 2011-03-01 15:20:52

+0

但我同意你所鏈接的文章:不要濫用子類,特別是不要將它用於錯誤的原因。 – jv42 2011-03-01 15:23:35