Denis Kharitonov
Denis Kharitonov

Reputation: 209

Can't reorder rows in UITableView

I have encountered an issue when trying to reorder rows in UITableView. I have the function tableView:moveRowAtIndexPath:toIndexPath: triggered, but fromIndexPath is equal to toIndexPath (i.e. source == destination). I saw the same issue here: uitableview re-order won't work, source always equal to destination But the solution was - to use different library. That is not a variant for me.

- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
    //fromIndexPath is equal to toIndexPath, so nothing is exchaned
    [self.table_data exchangeObjectAtIndex:fromIndexPath.row withObjectAtIndex:toIndexPath.row];
}

My table is in editable mode, I have canMoveRowAtIndexPath: returning YES. My it does not help. How come? What am I doing wrong?

Upvotes: 2

Views: 2029

Answers (2)

Denis Kharitonov
Denis Kharitonov

Reputation: 209

The problem was in custom pan gesture recognizer. It somehow was in conflict with rows drag-drop behavior

Setting myGestureRecognizer.cancelsTouchesInView = NO; fixed the issue

Upvotes: 10

Uttam Sinha
Uttam Sinha

Reputation: 722

Try this. It works.

- (void)viewDidLoad {
    [super viewDidLoad];
    arr = [NSMutableArray arrayWithObjects:@"First",@"Second",@"Third",@"Fourth", nil];    
    self.tableView.editing = YES;
}

#pragma mark - Table view data source

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    // Return the number of rows in the section.
    return arr.count;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cellIdentifier" forIndexPath:indexPath];

    UILabel *label = (UILabel *)[cell.contentView viewWithTag:100];
    [label setText:[arr objectAtIndex:indexPath.row]];

    return cell;
}

- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
    return YES;
}

- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)sourceIndexPath toIndexPath:(NSIndexPath *)destinationIndexPath
{
    NSString *stringToMove = arr[sourceIndexPath.row];
    [arr removeObjectAtIndex:sourceIndexPath.row];
    [arr insertObject:stringToMove atIndex:destinationIndexPath.row];
}

Check the screenshot -

enter image description here

enter image description here

Upvotes: 1

Related Questions