有人可以解释一下如何正确实现tableView:commitEditingStyle:forRowAtIndexPath:
方法,以便我可以正确删除支持数组中的项目并仅显示我尚未删除的项目吗?
这是我到目前为止所拥有的:
@interface ViewController : UIViewController <UITableViewDelegate,UITableViewDataSource>
{
IBOutlet UITableView *tableView;
NSArray *allItems;
NSMutableArray *displayItems;
}
@end
@implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
allItems = [[NSArray alloc] initWithObjects:@"One",@"Two",@"Three",@"Four",@"Five",@"Six",@"Seven", nil];
displayItems = [[NSMutableArray alloc] initWithArray:allItems];
}
-(UITableViewCell*) tableView:(UITableView *)aTableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
if (!cell) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cell"];
}
cell.textLabel.text = [displayItems objectAtIndex:indexPath.row];
return cell;
}
@end
答案 0 :(得分:3)
试试这个:
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
if (editingStyle == UITableViewCellEditingStyleDelete) {
// Delete the row from the data source.
[tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
if(!deletedIndices) deletedIndices = [[NSMutableIndexSet alloc] initWithIndex:indexPath.row];
else [deletedIndices addIndex:indexPath.row];
}
else if (editingStyle == UITableViewCellEditingStyleInsert) {
// Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view.
}
}
-(IBAction)editingDidComplete:(id)sender
{
// remove the objects from display array
[valueArray removeObjectsAtIndexes:deletedIndices];
// Reload tableView if needed
[mainTableView reloadData];
[mainTableView setEditing:NO];
}
答案 1 :(得分:3)
按如下方式实施tableView:commitEditingStyle:forRowAtIndexPath:
:
// Override to support editing the table view.
- (void)tableView:(UITableView *)aTableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
if (editingStyle == UITableViewCellEditingStyleDelete) {
// remove the object from display array
[displayItems removeObjectAtIndex:indexPath.row];
// Delete the row from the data source.
[aTableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
}
else if (editingStyle == UITableViewCellEditingStyleInsert) {
// Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view.
}
}