我正在使用带有情节提要的 xcode 4.2 来创建 iphone 应用程序。
当我按下右上角的编辑按钮时,我希望有选项来删除现有行并在顶部看到额外的单元格(带有绿色“+”图标),这将允许我添加新单元格。
我有一个正在填充的数组viewDidLoad
使用 CoreData 的方法
我已启用设置按钮
self.navigationItem.rightBarButtonItem = self.editButtonItem;
并实现了该方法
- (void)tableView:(UITableView *)tableView commitEditingStyle:
(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:
(NSIndexPath *)indexPath
{
if (editingStyle == UITableViewCellEditingStyleDelete) {
// removing a cell from my array and db here...
}
else if (editingStyle == UITableViewCellEditingStyleInsert) {
// adding a cell to my array and db here...
}
}
我意识到我需要在某个时候添加单元格,然后我可以对其进行编辑,但我不清楚在哪里,而且我无法在互联网上找到解释。
好的,基本思想是,当单击编辑按钮时,我们将在每行旁边显示删除控件,并使用添加控件添加一个新行,以便用户可以单击它来添加条目,对吗?首先,由于您已经设置了编辑按钮,让我们指示我们的表在编辑模式下应该显示额外的行。我们在我们的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
}
}
祝你好运,胃口好!
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)