繁体   English   中英

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

[英]UITableView bug when adding a UIButton programmatically

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

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

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

你做这个subBtnnewBtn指向最后一个单元格的按钮。 更好的方法是将UITableViewCell子类化并使按钮实例变量。 然后覆盖- (void)setEditing:(BOOL)editing animated:(BOOL)animated并隐藏/显示那里的按钮。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM