Objective:
Delete
in a row whenever it selectedAnd remove it whenever cell selection changes and so on add 'Delete' to last selection.
(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath*)indexPath{
self.myIndexPath=indexPath;
UIButton *btnCustomDelete=[[UIButton alloc] initWithFrame:CGRectMake(260, 10, 60, 7)];
[btnCustomDelete setTitle:@"Delete" forState:UIControlStateNormal];
[tblCellForContactTable.contentView addSubview: btnCustomDelete]; //I think correction wants here
[btnCustomDelete addTarget:self action:@selector(actionCustomDelete:) forControlEvents:UIControlEventTouchUpInside];
}
-(IBAction) actionCustomDelete:(id)sender{
[arrForMyContacts removeObject:[arrForMyContacts objectAtIndex:myIndexPath.row]];
[tblForContacts reloadData];
}
But, its not worked all time.
You are right. You should add button as a subview to your actual UITableViewCell
object, which you can achieve using tableView:cellForRowAtIndexPath:
data source method.
So, your implementation can be something like (after creating your btnCustomDelete
):
UITableViewCell * myCell = [tableView cellForRowAtIndexPath:indexPath]
[myCell.contentView addSubview:btnCustomDelete];
Please keep reading.
Your implementation is not a healthy solution to delete a row from a table. You can have delete action easily with implementing some UITableView
data source and delegate methods, without adding a custom button, like below:
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
return YES;
}
- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath
{
return UITableViewCellEditingStyleDelete;
}
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
[arrForMyContacts removeObjectAtIndex:indexPath.row];
[tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
}