以编程方式添加UIButton时的UITableView错误

时间:2012-01-08 23:35:48

标签: iphone ios cocoa-touch uitableview uibutton

我有一个表格视图。我为每个单元格添加了两个按钮:

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

    cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil)
     {
    cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
        newBtn = [[UIButton alloc]init];
         newBtn=[UIButton buttonWithType:UIButtonTypeRoundedRect];
         [newBtn setFrame:CGRectMake(250,10,25,55)];
         [newBtn addTarget:self action:@selector(addLabelText:) forControlEvents:UIControlEventTouchUpInside];
         [newBtn setTitle:@"+" forState:UIControlStateNormal];
         [newBtn setEnabled:YES];
         newBtn.hidden = YES;
         [cell addSubview:newBtn];

         subBtn = [[UIButton alloc]init];
         subBtn=[UIButton buttonWithType:UIButtonTypeRoundedRect];
         [subBtn setFrame:CGRectMake(280,10,25,55)];
         [subBtn addTarget:self action:@selector(subtractLabelText:) forControlEvents:UIControlEventTouchUpInside];
         [subBtn setTitle:@"-" forState:UIControlStateNormal];
         [subBtn setEnabled:YES];
         subBtn.hidden = YES;
         [cell addSubview:subBtn];

    } 
return cell;
}

我希望首先隐藏按钮,然后当桌子处于“编辑”模式时,我希望这些按钮出现。当表离开“编辑”模式时,按钮消失。

我可以通过其中一个单元格按钮来执行此操作。

    - (IBAction)editButton:(id)sender 
{
    if (self.editing) 
    {
        [self setEditing:NO animated:YES];
        [self.myTableView setEditing:NO animated:YES];
        EditButton.title = @"Edit";
        subBtn.hidden = YES;
        newBtn.hidden = YES;
    } 
    else 
    {
        [self setEditing:YES animated:YES];
        [self.myTableView setEditing:YES animated:YES];
        EditButton.title = @"Done";
        subBtn.hidden = NO;
        newBtn.hidden = NO;
    }
}

但问题是:当我这样做时,只有最后一个单元格才能获得按钮。它们在我想要的时候出现和消失,但只有最后一个细胞!没有其他细胞得到任何按钮,有人可以帮助我!非常感谢!

2 个答案:

答案 0 :(得分:1)

您执行此操作的方式subBtnnewBtn指向最后一个单元格的按钮。更好的方法是子类UITableViewCell并使按钮实例变量。然后覆盖- (void)setEditing:(BOOL)editing animated:(BOOL)animated并隐藏/显示那里的按钮。

答案 1 :(得分:1)

你如何触发“编辑”按钮'方法?如果您使用的是didSelectRowAtIndexPath,则只有选定的行才会显示按钮。您可以遍历indexpath.row查看可见单元格,取消隐藏每一行。