簡體   English   中英

使用自定義UIButton刪除UITableViewCell

[英]Delete UITableViewCell using custom UIButton

我嘗試使用自定義按鈕刪除單元格時遇到此錯誤。

*由於未捕獲的異常'NSRangeException'而終止應用程序,原因:'* -[__ NSArrayM removeObjectAtIndex:]:索引1超出范圍[0 .. 0]'

這是我的代碼的結構。 我有一個自定義UITableViewCell ,其中包含一個UIButton ,該UIButton具有刪除單元格的操作。 刪除單元格的操作在主View控制器中,該控制器包含單元格的實際indexPath 這種結構工作正常。

這是刪除單元格的操作。

NSIndexPath *indexPath = [self globalIndexPath];

[self.array removeObjectAtIndex:[indexPath row]];
[db deleteTaskAtIndex:[indexPath row]];

[self.tableView deleteRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath,nil] withRowAnimation:UITableViewRowAnimationFade];

當我聲明上面的indexPath ,在我的cellForRowAtIndexPath設置了globalIndexPath屬性,為其提供了原始indexPath的值。 這就是我宣布的方式。

[self setGlobalIndexPath:indexPath];

現在,我在此處放置了一些NSLogs來記錄indexPath 例如,在viewWillAppear方法和viewDidLoad方法中,它們都給了我准確的indexPath ,甚至檢查了array輸出,並且它們都返回了准確的結果,所以我真的不知道為什么它給了我錯誤。

這是我的自定義單元中的代碼,用於檢測點擊按鈕的時間。

NSArray *notificationArray = [[UIApplication sharedApplication] scheduledLocalNotifications];
if (!notificationArray || !notificationArray.count)
{
    [[NSNotificationCenter defaultCenter] postNotificationName:@"DeleteSignal" object:nil];
}
else
{
    UILocalNotification *notif = [notificationArray objectAtIndex:[checkbox tag]];
    [[UIApplication sharedApplication] cancelLocalNotification:notif];
}

然后,我使用NSNotificationCenter並通過鍵DeleteSignal刪除單元格。

如果要在cellForRowAtIndexPath中設置globalIndexPath(並且在其他任何地方都沒有設置),則globalIndexpath將始終知道最后一個創建或出隊的單元的indexPath,而不是用戶可能實際使用該按鈕的那個。 似乎已被設計破壞。 還是您的細胞大到只有一個可見?

首先,我會嘗試在cellForRowAtIndexPath設置單元格的UIButton的標簽

myButton.tag = indexPath.row + SOMEOFFSETTOASSUREYOURTAGDOESNTGET0;

然后通過以下標記在操作中獲取indexPath:

NSIndexPath *indexPath = [NSIndexPath indexPathForRow:(UIButton*)sender.tag - OFFSET inSection:0];

當然,僅當您只有一個部分時,此方法才有效。 如果需要處理多個部分,則可以使用包含所有indexPath的數組,並將UIButton的標簽設置為數組中該indexPath的索引。

UPDATE

從技術上來說,可以(錯誤地)使用NSNotificationCenter做您的工作,但我還是建議您逐步閱讀本教程

暫無
暫無

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

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