簡體   English   中英

嘗試動態地向iOS中的UITableView添加新行

[英]Trying to add a new row dynamically to a UITableView in iOS

我在我的應用程序中有一個UITableView,我試圖通過單擊按鈕動態添加行。 當用戶單擊我的按鈕時,將調用以下方法:

- (IBAction)addChoice:(id)sender {
    //addRow is a boolean variable that is set so that we can use it to check later and add a new row
    if (!self.addRow) {
        self.addRow = YES;
    }

    [self setEditing:YES animated:YES];
}

然后調用:

- (void)setEditing:(BOOL)editing animated:(BOOL)animated {

    [super setEditing:editing animated:animated];
    [self.choiceTable setEditing:editing animated:animated];

}

問題是,盡管我已經實現了UITableViewDelegate和UITableViewDataSource,但我已經調用了以下任何一個委托方法:

- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath {

    if (self.addRow) {
        return UITableViewCellEditingStyleInsert;
    } else {
        return UITableViewCellEditingStyleDelete;
    }
}


- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {

    NSArray *indexPathArray = [NSArray arrayWithObject:indexPath];

    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [self.tableData removeObjectAtIndex:indexPath.row];
        NSArray *indexPathArray = [NSArray arrayWithObject:indexPath];
        [tableView deleteRowsAtIndexPaths:indexPathArray withRowAnimation:UITableViewRowAnimationFade];
    } else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
        NSString *theObjectToInsert = @"New Row";
        [self.tableData addObject:theObjectToInsert];
        [tableView reloadData];
        [tableView insertRowsAtIndexPaths:indexPathArray withRowAnimation:UITableViewRowAnimationAutomatic];
    }   
}

任何人都可以看到它我做錯了什么?

您需要在表數據數組中插入一行,然后在tableview上調用insertRowsAtIndexPaths ,讓表視圖知道新行。 新行將位於數組的末尾,因此行count-1。

[self.tableData addObject:newObject];
NSIndexPath *newPath=[NSIndexPath indexPathForRow:self.tableData.count-1 inSection:0];
[self.tableView insertRowsAtIndexPaths:@[newPath] withRowAnimation:UITableViewRowAnimationAutomatic];

您應該在UITableView上執行插入或刪除,如下所示:

[tableView beginUpdates];

// Add object to the array
[self.tableData addObject:theObjectToInsert];

// perform tableView insertion/delete here
[tableView insertRowsAtIndexPaths:indexPathArray withRowAnimation:UITableViewRowAnimationAutomatic];

[tableView endUpdates];

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM