2012-07-21 62 views
0

NSMutableArray *objects包含一些對象,我用它來顯示我的表視圖單元格的內容。如果objects.count是0,我想使我的表視圖的編輯模式時viewDidLoad表視圖:setEditing以編程方式

- (void)viewDidLoad { 

    // If there is no content to present enable editing mode 
    if (self.objects.count == 0) [self setEditing:YES animated:YES]; 
} 

這將觸發self.editButtonItem並插入一個新行(說明「點擊此處將新元素添加」)到我的表觀點:

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

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

    if (self.editing) { 
     [self.tableView insertRowsAtIndexPaths:[NSArray arrayWithObject:[NSIndexPath indexPathForRow:[self.objects count] inSection:0]] 
           withRowAnimation:UITableViewRowAnimationAutomatic]; 
    } 

    else { 
     [self.tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:[NSIndexPath indexPathForRow:[self.objects count] inSection:0]] 
           withRowAnimation:UITableViewRowAnimationAutomatic]; 
    } 
} 

不幸的是這種設置導致崩潰:

*** Assertion failure in -[UITableView _endCellAnimationsWithContext:], /SourceCache/UIKit/UIKit-1914.85/UITableView.m:833 

是沒可能切換編輯MOD通過編程?如果用戶觸摸self.editButtonItem一切正常 - 並且據我所知,這個editButton與我在viewDidLoad中做的一樣。

我在做什麼錯?

回答

1

我認爲這裏有兩個不同的問題。

一,有可能以編程方式執行setEditing:animated:

但我不認爲這就是你真正想在這裏做的。編輯模式是供用戶手動編輯表格,如果您設置了這些設置,則會顯示左側的小紅色按鈕,並且可能會顯示右側的小動態指示器。

要做的更好的事情是,當您發現對象已更改,執行[self.tableView reloadData];,並確保您的UITableViewDataSource協議方法執行正確的事情。這將包括執行tableView:numberOfRowsInSection:(也可能是numberOfSections)和tableView:cellForRowAtIndexPath:。這會導致項目出現在tableView中,如objects所做的更改。

+0

感謝您的回答。我認爲這是一個誤解:我確實希望我的tableview在我的「點擊此處添加一個新元素」行旁邊顯示紅色小按鈕。所以它看起來應用程序已經點擊了用戶的「編輯」按鈕。在點擊「編輯」按鈕之前,視圖是空的,因爲tableview沒有數據要顯示。所以用戶在任何情況下都會點擊「編輯」按鈕。爲了保存這一步,我想以編程方式啓用編輯模式。 – Patrick 2012-07-21 18:17:26

+1

如果這就是你想要實現它,那麼仍然做所有我推薦的東西,使tableView與對象的變化一起出現,並使用setEditing實現:animated:僅在調用super和self.tableView時才實現,並且不要在setEditing:animated:調用中執行插入和刪除操作。意識到對於用戶刪除的任何內容,您還必須實現tableView:commitEditingStyleForRowAtIndexPath:。如果您在編輯時實施了添加項目的方法,情況也會如此。 – 2012-07-21 18:44:59

+0

您的注意事項不要在'setEditing:animated:'內執行插入和刪除操作,實際上幫助我解決了這個問題:我現在使用正確的方法來處理這個問題,使用我的'tableView:numberOfRowsInSection: :animated:'我正在重新載入我的表格視圖的內容 - 就像您在原始答案中推薦的一樣。再次感謝! – Patrick 2012-07-22 10:45:12