Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
251 views
in Technique[技术] by (71.8m points)

ios - change Table to Edit mode and delete Rows inside a normal ViewController

I just inserted a table into a normal UIViewController and connected the delegate and source components with the file's owner. Everything works fine when i insert data into the table rows. but now i am trying to find out how rows can be deleted.

I just looked at a lot of other posts, but couldn't find the right solution.

I tried to insert a asseccory button for each row in the table:

cell.accessoryType = UITableViewCellAccessoryDetailDisclosureButton;

i even found the method that will be called when the accessory button is pressed:

- (void)tableView:(UITableView *)tableView accessoryButtonTappedForRowWithIndexPath:(NSIndexPath *)indexPath{

    NSLog(@"Accessory pressed");

    //[self tableView:tableView willBeginEditingRowAtIndexPath:indexPath];

    //[self tableView:nil canEditRowAtIndexPath:indexPath];
    //[self setEditing:YES animated:YES];
}

Inside the log the message is printed, but no one of the methods that i tried to call (the commented one) did change the view to the edit mode. How can i solve this problem?


Here is a Screenshot of the UIViewController. I haven't integrated a navigationController.

enter image description here

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

In order to enable edit mode for table view, you can call edit method on UITableView as,

[self.tableView setEditing:YES animated:YES];

You have to implement tableView:commitEditingStyle:forRowAtIndexPath: method to enable the deleting of rows. In order to delete the rows you need to use deleteRowsAtIndexPaths:withRowAnimation: method.

For eg:-

self.navigationItem.rightBarButtonItem = self.editButtonItem;//set in viewDidLoad

- (void)setEditing:(BOOL)editing animated:(BOOL)animated { //Implement this method
    [super setEditing:editing animated:animated];
    [self.tableView setEditing:editing animated:animated];
}

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath { //implement the delegate method

  if (editingStyle == UITableViewCellEditingStyleDelete) {
    // Update data source array here, something like [array removeObjectAtIndex:indexPath.row];
    [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
  }   
}

For more details check the apple documentation here.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...