我有一個自定義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的兩個不同部分,所以我認爲這不會起作用。
也許它只是我,但按鈕的代碼看起來完全一樣。 – 2011-03-01 13:03:15
也許你的代碼並不是真的那樣,但你並沒有添加你創建的同一個按鈕(myButton vs damageButton)。 – jv42 2011-03-01 13:24:31
@fluchtpunkt - 唯一的區別是目標是一個視圖控制器,我作爲一個屬性傳遞 – DVG 2011-03-01 14:23:32