Making selecting a row and swipe left behave same in tableviewcontroller

557 Views Asked by At

I am trying to make swipe-left and click on a tableview cell behave exactly the same. I couldn't find a direct answer to this..

I have a tableView and the following code to make sure cell highlighting happens on click

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [self selectRowAtIndexPath:indexPath];
}

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


- (void)setCellColor:(UIColor *)color ForCell:(UITableViewCell *)cell {
    cell.contentView.backgroundColor = color;
    cell.backgroundColor = color;
}

- (void)tableView:(UITableView *)tableView didHighlightRowAtIndexPath:(NSIndexPath *)indexPath {
    // Add your Colour.
    [self setCellColor:[UIColor colorWithWhite:0.961 alpha:1.000] ForCell:[tableView      cellForRowAtIndexPath:indexPath]];  //highlight colour
}

- (void)tableView:(UITableView *)tableView didUnhighlightRowAtIndexPath:(NSIndexPath *)indexPath {
    // Reset Colour.
    [self setCellColor:[UIColor whiteColor] ForCell:[tableView cellForRowAtIndexPath:indexPath]];     //normal color
}

I also have the following code for swipe left gesture on a cell

- (void)handleSwipeLeft:(UISwipeGestureRecognizer *)gestureRecognizer
{
    //Get location of the swipe
    CGPoint location = [gestureRecognizer locationInView:self.tblView];

    //Get the corresponding index path within the table view
    NSIndexPath *indexPath = [self.tblView indexPathForRowAtPoint:location];

    //Check if index path is valid
    if(indexPath)
    {
        [self.tblView selectRowAtIndexPath:indexPath animated:NO scrollPosition:UITableViewScrollPositionNone];
        [self.tblView.delegate tableView:self.tblView didSelectRowAtIndexPath:indexPath];
    }
}

The swipe gesture happens properly, ie it behaves same as a click, but it doesn't highlight the cell. I tried forcing a highlight inside the leftSwipe gesture by setting color of the cell, it still doesn't work. Any suggestions ? Thanks

1

There are 1 best solutions below

0
On

What worked for me is to set SelectionStyle to None in cellForRowAtIndexPath. If I don't set the style, it will not show the selection color immediately after I select a cell, which is covered by a gray color.

[cell setSelectionStyle:UITableViewCellSelectionStyleNone];

And in didSelectRowAtIndexPath, set your cell selection color.

cell.backgroundColor = [UIColor brownColor];

You can remove the following line because

it will not call the delegate methods (-tableView:willSelectRowAtIndexPath: or tableView:didSelectRowAtIndexPath:), nor will it send out a notification.

[self.tableView selectRowAtIndexPath:indexPath animated:YES scrollPosition:UITableViewScrollPositionNone]