【问题标题】:Actions for UIButtons in UITableViewCellsUITableViewCells 中 UIButton 的操作
【发布时间】:2011-11-03 11:14:14
【问题描述】:

我在 UITableView 的每个单元格中实现了一个 UIButton,并为此按钮设置了一个操作。现在我试图找出这些按钮中的哪一个被点击了:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
    }

    // Configure the cell...
    <...>

    UIButton *but=[UIButton buttonWithType:UIButtonTypeRoundedRect];
    but.frame= CGRectMake(275, 5, 40, cell.frame.size.height-10);
    [but setTitle:@"Map" forState:UIControlStateNormal];
    [but addTarget:self action:@selector(Map:) forControlEvents:UIControlEventTouchUpInside];

    [cell.contentView addSubview:but];

    [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
    return cell;

}

- (IBAction) Map: (id) sender {
    NSIndexPath *indexPath = [[NSIndexPath alloc] init];
    indexPath = [tableView indexPathForCell:(UITableViewCell*)[[sender superview]superview]];
    [delegate callMap: [[[data objectAtIndex:indexPath.section] 
                         objectAtIndex:indexPath.row+1] 
                        objectAtIndex:kNameInArray]

                     : [[[[data objectAtIndex:indexPath.section] 
                          objectAtIndex:indexPath.row+1] 
                         objectAtIndex:kXcoordinateInArray] doubleValue]

                     : [[[[data objectAtIndex:indexPath.section] 
                          objectAtIndex:indexPath.row+1] 
                         objectAtIndex:kYcoordinateInArray] doubleValue]
     ];
}

但它总是将data[0][1][*] 元素发送给委托。我的意思是indexPath 总是有 0 个原始和 0 部分。我的错在哪里?

【问题讨论】:

  • 我认为你不需要在这里分配一个 NSIndexPath: NSIndexPath *indexPath = [[NSIndexPath alloc] init];

标签: ios uitableview


【解决方案1】:

执行以下操作: 在您的 if (cell == nil) { ... } 方法中添加按钮,否则当您的单元格被重复使用时,您将在同一个单元格内有很多按钮。
在返回单元格之前设置cell.contentViow.tag = SomeValueIdentifyingYourData(一些代表您的模型的 int 值..可能只是您的对象数组的索引..)。
在您的 Map: 方法中,您可以使用 ((UIButton)sender).superview.tag 再次访问该值并根据该值做出决定

【讨论】:

  • 这对我有用,现在我知道按下了哪个按钮,但如果像你说的那样显示按钮有问题:它在另一个视图下卡住了,所以只有一部分(右边几个像素侧面)显示出来。
  • 用框架和自动调整蒙版进行实验 :)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-05-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多