簡體   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