添加您的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];