好的,基本的想法是,當單擊編輯按鈕時,我們將顯示每行旁邊的刪除控件,並添加一個新的行與添加控件,使用戶可以點擊它,以添加一個條目右?首先,由於您已經設置了編輯按鈕,所以讓我們指導我們的表格,在編輯模式下,我們應該顯示額外的一行。我們這樣做,在我們的tableView:numberOfRowsInSection
:
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return self.editing ? a_recs.count + 1 : a_recs.count;
}
a_recs
這裏是我設置存儲我們的記錄,所以你要切換說出來用自己的陣列的方向。接下來,我們告訴我們的tableView:cellForRowAtIndexPath:
做什麼用的額外的行:
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSString *CellIdentifier = @"Cell";
BOOL b_addCell = (indexPath.row == a_recs.count);
if (b_addCell) // set identifier for add row
CellIdentifier = @"AddCell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
if (!b_addCell) {
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
}
}
if (b_addCell)
cell.textLabel.text = @"Add ...";
else
cell.textLabel.text = [a_recs objectAtIndex:indexPath.row];
return cell;
}
我們也希望我們的指示表中爲添加行,我們希望添加圖標
-(UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath {
if (indexPath.row == a_recs.count)
return UITableViewCellEditingStyleInsert;
else
return UITableViewCellEditingStyleDelete;
}
黃油。現在超級祕密功夫醬,用筷子把它們全部放在一起:
-(void)setEditing:(BOOL)editing animated:(BOOL)animated {
[super setEditing:editing animated:animated];
[self.tableView setEditing:editing animated:animated];
if(editing) {
[self.tableView beginUpdates];
[self.tableView insertRowsAtIndexPaths:[NSArray arrayWithObject:[NSIndexPath indexPathForRow:a_recs.count inSection:0]] withRowAnimation:UITableViewRowAnimationLeft];
[self.tableView endUpdates];
} else {
[self.tableView beginUpdates];
[self.tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:[NSIndexPath indexPathForRow:a_recs.count inSection:0]] withRowAnimation:UITableViewRowAnimationLeft];
[self.tableView endUpdates];
// place here anything else to do when the done button is clicked
}
}
祝你好運和好胃口!
:))沒問題! – ragamufin 2012-03-26 20:08:57
使用此方法時,我注意到我們添加和刪除的插入行在刪除它時會在右側顯示藍色選擇圖標。它必須在刪除行之前將表從編輯模式中取出。我試着將'beginUpdates'調用放在tableView'setEditing'調用的上方,但是當添加行時出現藍色圖標,而不是刪除。任何想法如何避免這個藍色選擇圖標? – Ryan 2013-01-08 02:05:18
聽起來像accessoryType被設置在某個地方或緩存在tableView隊列中。嘗試在添加單元格時將其明確設置爲UITableViewCellAccessoryNone。 – ragamufin 2013-01-08 18:16:52