iphone - 在不使用标签的情况下在按钮操作方法中传递参数

标签 iphone objective-c ios uitableview uibutton

我正在动态创建按钮。和创建操作方法

  [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/

相关文章:

ios - 亚马逊 Cognito 与 SwiftUI

iphone - @2x.png 也需要非@2x.png 大小?

iphone - 如何用这一行解决 Thread1 : Signal SIGABRT ? [[NSBundle mainBundle] loadNibNamed: @"DVDListingView"Owner:self options:nil];

objective-c - 使用条件运算符的 else do not 相当于什么?

iphone - 关于 CLLocation Manager 和多个 ViewController 的一些架构问题

ios - 在 Swift 中画线

iphone - 从 CAShapeLayer 获得真正糟糕的性能

ios - UISearchBar - ReturnKeyType 不适用于 iOS 8

ios - UIAlertController 和 UIAlertControllerStyleActionSheet 自定义

ios - 检查 key 是否存在 firebase 4 和 swift 4?