簡體   English   中英

如何從其他ViewController的表視圖中刪除行

[英]How to Delete Row from Table View from other ViewController

所以我有一個DetailViewController,它從表視圖顯示行/單元格的詳細信息。 現在,我想在此控制器上添加一個DELETE選項。 我在上面添加了一個Bar Button項目(垃圾箱)。 如何才能刪除當前行/數據並將其也從TableViewController中刪除?

TableViewController

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {

    WishlistItem *wish = [self.wishlistItem objectAtIndex:indexPath.row];

    DetailViewController *dvc = [self.storyboard instantiateViewControllerWithIdentifier:@"dvcID"];
    dvc.wishItemStr = wish.wishlistItem;
    dvc.dateItemStr = wish.targetDate;
    dvc.descItemStr = wish.descWishItem;

    [self.navigationController pushViewController:dvc animated:YES];
}

創建詳細視圖控制器時,必須使用一些與該行相關的數據對其進行初始化。 因此,您可以擴展占用一個塊的那個初始化方法(或者如果願意,可以添加一個新方法)。 當表視圖控制器創建並加載詳細視圖控制器時,它將使用一些將刪除相關行的塊代碼對其進行初始化。

示例:(請注意,我尚未對此進行編譯)。

Add this to the DetailViewController:

    @property (copy, nonatomic) void (^deleteRowBlock)(void);
    - (void) onDeletion:(void (^)(void)) deletionBlock;

The implementation of onDeletion is

- (void) onDeletion:(void (^)(void)) deletionBlock
{
    self.deleteRowBlock = deletionBlock;
}


When the button is pressed in the DetailViewController call the block like this:

    self.deleteRowBlock();


Then in didSelectRowAtIndexPath: add this:

            [dvc onDeletion:^{
                code to delete the row and update your data model
            }];

然后,當按下按鈕時,將執行“刪除行並更新數據模型的代碼”。

或者,如果您不喜歡塊(但您應該學習喜歡它們),則使用諸如onDelete:(NSIndexPath *)row之類的方法定義協議。 表格視圖是詳細視圖的委托,並實現協議方法,您可以在按下按鈕時調用該協議方法。 詳細視圖將需要知道其行號。 可替代地移除NSIndexPath作為參數傳遞給onDelete和具有的tableView緩存當前呈現的詳細視圖控制器的行數,並且當onDelete被調用時將刪除緩存行數的行。 但是最好使用塊

好,這是另一種解決方案,

1)將self.wishListItem傳遞給DetailViewController,這是示例

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    DetailViewController *dvc = [self.storyboard instantiateViewControllerWithIdentifier:@"dvcID"];
    ...
    [dvc setWishListItem:self.wishListItem];
    ...
    [self.navigationController pushViewController:dvc animated:YES];
}

2)在TableViewController中實現這樣的viewWillAppear方法

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self.tableView reloadData];
}

3)在DetailViewController中,您有一個刪除按鈕,對嗎? 這是您按鈕的操作方法

- (void)onDelete {
    // your deleting stuff ...
    [self.wishListItem removeObjectAtIndex:self.currentItemIndex];  // this line updates shared data
}

因此,TableViewController重新加載其數據,並在您返回時保持單元格為最新(例如,通過觸摸“后退”按鈕)

如果您仍有問題,請隨時發表評論。

暫無
暫無

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

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