添加您UIButton
像這樣
UIButton *btn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[btn setFrame:CGRectMake(10.0, 2.0, 140.0, 40.0)];
[btn setTitle:@"ButtonTitle" forState:UIControlStateNormal];
[btn addTarget:self action:@selector(buttonClicked:) forControlEvents:UIControlEventTouchUpInside];
[btn setTag:indexPath.row];
[cell.contentView addSubview:btn];
,然後獲取其標籤號 -
-(void)buttonClicked:(id)sender
{
NSLog(@"tag number is = %d",[sender tag]);
//In this case the tag number of button will be same as your cellIndex.
// You can make your cell from this.
NSIndexPath *indexPath = [NSIndexPath indexPathForRow:[sender tag] inSection:0];
UITableViewCell *cell = [tblView cellForRowAtIndexPath:indexPath];
}
注:上述解決方案,當你的tableView只有1節會工作。如果你的tableView有多個部分,你應該知道你的部分索引或去下面的方法。
備選:1
UIView *contentView = (UIView *)[sender superview];
UITableViewCell *cell = (UITableViewCell *)[contentView superview];
NSIndexPath *indexPath = [tblView indexPathForCell:cell];
備選:2
CGPoint touchPoint = [sender convertPoint:CGPointZero toView:tblView];
NSIndexPath *indexPath = [tblView indexPathForRowAtPoint:touchPoint];
UITableViewCell *cell = [tblView cellForRowAtIndexPath:indexPath];
您可以根據您的單元格的行數爲您的按鈕設置標籤,然後您可以輕鬆獲取cellIndex。顯示你在單元格(cellForRowAtIndexPath :)方法中添加按鈕的代碼? – TheTiger 2012-08-13 14:16:53
@VakulSaini謝謝。我沒有從(id)發件人獲取cellIndex。我已編輯我的問題,請查看此。謝謝。 – 2012-08-13 14:20:18
你正在得到這個,因爲你正在打印'UIButton'的id。 看我的帖子得到cellIndex – TheTiger 2012-08-13 14:26:59