tags:

views:

191

answers:

2

I've got a UITableViewDataSource that I'm using for two different UITableViews. In one of the table views, I want to enable swipe-to-delete, so I've implemented tableView:commitEditingStyle:forRowAtIndexPath, and it works as expected. However, in another table, I want to disable that feature.

I've got it working by making two UITableViewDataSource classes, one subclassing the other, and I only implement tableView:commitEditingStyle:forRowAtIndexPath in the subclass. I call them RecipientModel and RecipientModelEditable.

I'm wondering if there's a better way.

+2  A: 

You could make two instances of the same class RecipientModel. Set a BOOL instance variable, perhaps named isEditable. Your interface might look like this:

@interface RecipientModel : NSObject <UITableViewDataSource> {
    BOOL isEditable;
}

@property ( readwrite ) BOOL isEditable;

@end

And your implementation might look like this:

@implementation RecipientModel

@synthesize isEditable;

- ( void )tableView:( UITableView * )tableView
 commitEditingStyle:( UITableViewCellEditingStyle )editingStyle
  forRowAtIndexPath:( NSIndexPath * )indexPath
{
    if ( self.isEditable ) {
        // Allow swipe.
    } else {
        // Disallow swipe.
    }
}

@end

One thing to note is that most iPhone apps use a UITableViewController to implement their table view's data source and delegate methods. That approach may also make more sense for your application.

Jeff Kelley
Yes, but how do I "disallow swipe" in the `tableView:commitEditingStyle:forRowAtIndexPath`? By simply defining the method, the user is able to swipe to *see* the delete button. I don't want it to show up at all.
synic
Do you want the cell to be editable? If not, then you could get around this by returning `NO` in `-tableView:canEditRowAtIndexPath:`. Otherwise, if merely defining the method is enough to do it, you'll have to resort to your subclassing method or start messing around with the Objective-C runtime.
Jeff Kelley
Also, see this: http://stackoverflow.com/questions/969313/uitableview-disable-swipe-to-delete-but-still-have-delete-in-edit-mode
Jeff Kelley
+1  A: 

I think you mean something like this:

- (UITableViewCellEditingStyle)tableView:(UITableView *)aTableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (self.isEditable) {
        return UITableViewCellEditingStyleDelete;
    }
    return UITableViewCellEditingStyleNone;
}

and then in the commitEditingStyle, don't do anything if its not editable

OTisler