Iphone 以编程方式添加UIButton时出现UITableView错误

Iphone 以编程方式添加UIButton时出现UITableView错误,iphone,ios,cocoa-touch,uitableview,uibutton,Iphone,Ios,Cocoa Touch,Uitableview,Uibutton,我有一张桌子。我在每个单元格中添加了两个按钮: - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath: (NSIndexPath *)indexPath { static NSString *CellIdentifier = @"Cell"; cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]

我有一张桌子。我在每个单元格中添加了两个按钮:

 - (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;
    }
}

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

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

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

我只是从导航栏上的按钮调用此方法,谢谢您的帮助!你能解释清楚一点吗?我是个笨蛋!哈哈,你说的“副呼叫”是什么意思?另外,如果不是太麻烦的话,你能不能提供一些示例代码,这样我可以研究它并在我的程序中使用它?谢谢你的帮助!另外,我的按钮如何“指向”最后一个单元格的按钮?我不知道是什么代码做的!再次感谢!:DI的意思是“子类”。每次执行“subBtn=[[UIButton alloc]init];”时,您的指针都会被覆盖,因此在结束时它指向最后一个单元格的按钮。我不知道如何更好的解释好吧我明白你的意思。然而,我不确定如何修复它。我应该分配并初始化
init
方法中的按钮吗?谢谢你的帮助!