我正在动态创建按钮。和创建操作方法
[newButton addTarget:self action:@selector(goToNew:)forControlEvents:UIControlEventTouchUpInside];
我想从 tableview 发送参数 (indexpath.row),但不想使用标签。因为我需要标签对所有按钮都保持相同,我如何在按钮操作中传递参数?
实际上我在每个 tableview 单元格中添加按钮,并且我想要对所有这些按钮进行操作,但是如果我使用 tag = indexpath.row 并将其与操作一起使用,它可以工作但是会发生覆盖按钮的问题。因此我想要标签将保持不变。
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = @"Cell";
UIButton *btn;
UITableViewCell *cell = (UITableViewCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:CellIdentifier] autorelease];
btn = [UIButton buttonWithType:UIButtonTypeCustom];
[btn addTarget:self action:@selector(goToNew:) forControlEvents:UIControlEventTouchUpInside];
btn.tag = 55;
[cell.contentView addSubview:btn];
}
else {
btn = (id)[cell.contentView viewWithTag:55];
}
return cell;
- (void) goToNew:(id)sender
{
UIButton *b = (UIButton *)sender;<br/>
UITableViewCell cell = (UITableViewCell)[b superview];
int row = [msgTableView indexPathForCell:cell].row;<br/>
(@"行是:::%d",行);
}
最佳答案
通过执行以下代码,您将获得 indexPath.row 而无需设置按钮标签。
- (IBAction)goToNew:(id)sender
{
UIButton *btn = (UIButton*) sender;
UITableViewCell *cell = (UITableViewCell*) [btn superview];
NSIndexPath *indexPath = [tableView indexPathForCell:cell];
int row = indexPath.row;
}
关于iphone - 在不使用标签的情况下在按钮操作方法中传递参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7347738/