I'm trying to delete a row in table view after confirmation from the user, using an alert view. However I don't know how to let the UIAlertViewDelegate
method know which row in the table to delete.
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
if (editingStyle == UITableViewCellEditingStyleDelete) {
UIAlertView *alert_delete = [[UIAlertView alloc]initWithTitle:[NSString stringWithFormat:@"Confirm Delete %@",[names objectAtIndex:indexPath.row] ] message:@"Warning all student data will be earsed" delegate:self cancelButtonTitle:@"Dismess" otherButtonTitles:@"YES", nil];
[alert_delete show];
// Delete the row from the data source
[tableView deleteRowsAtIndexPaths:@[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
}
}
in alert method i try handle it to delete row from table and database
-(void) alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
NSString*title = [alertView buttonTitleAtIndex:buttonIndex];
if ([title isEqualToString:@"YES"]) {
// how to pass indexPath.row to alertview
[names removeObjectAtIndex:indexPath.row];
}
}
If you want to pass something to the delegate then add a property to the delegate class and pass the information to it before invoking the alert view:
@interface AlertDelegate : NSObject <UIAlertViewDelegate>
@property (nonatomic) NSIndexPath *indexPath;
@end
// @implementation AlertDelegate omitted
And use thus:
UIAlertView *alertView = ...;
AlertDelegate *delegate = [AlertDelegate new];
alertView.delegate = delegate;
delegate.indexPath = indexPathFromSomewhere;
[alertView show]; // or whatever
If the delegate is self
, then that means adding the property to self
(or use a private instance variable).
In the delegate method you then have access to the indexPath:
-(void) alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
NSString*title = [alertView buttonTitleAtIndex:buttonIndex];
if ([title isEqualToString:@"YES"]) {
[names removeObjectAtIndex:self.indexPath.row];
}
}