indexPathForRowAtPoint не даст мне правильный индекс - PullRequest
2 голосов
/ 10 ноября 2010

Я пытаюсь реализовать твиттер-приложение для iPhone, например интерфейс.(Проведите пальцем, чтобы заменить представление в ячейке табличного представления на пользовательское представление).Я использую UISwipeGestureRecognizer от Apple, чтобы распознать удар, и я получаю начальное местоположение для этого удара, используя [recognizer locationInView:self.view].Это дает мне CGPoint, и я использую это с [tableView indexPathForRowAtPoint:location].Моя проблема в том, что мое перелистывание всегда, кажется, обнаруживается в одной строке выше или ниже фактической строки, в которой я проводил. Кто-нибудь сталкивался с такой же проблемой?Я использую пользовательскую ячейку просмотра таблицы, и ее высота больше, чем представление по умолчанию.Я не уверен, имеет ли это какое-то значение, я использую heightForRowIndexAtPath:, чтобы вернуть высоту.

Мой код -

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
ModelObject *rowData = (ModelObject *)[tempArr objectAtIndex:indexPath.row];
if (rowData.isAlternateView) {
        // Load alternateview
    UISwipeGestureRecognizer *recognizer = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(handleSwipe:)];
    [recognizer setDirection:(UISwipeGestureRecognizerDirectionRight)];
    [cell addGestureRecognizer:recognizer];
    [recognizer release]; 
    return cell;

}
else {
    // Load the correct uitableviewcell
    UISwipeGestureRecognizer *recognizer = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(handleSwipe:)];
    [recognizer setDirection:(UISwipeGestureRecognizerDirectionRight)];
    [cell addGestureRecognizer:recognizer];
    [recognizer release]; 

    return cell;
}

}


-(void) handleSwipe:(UISwipeGestureRecognizer *) recognizer
{
NSLog(@"Swipe detected!");
CGPoint location = [recognizer locationInView:self.view];   
NSIndexPath *selectedIndexPath = [tableView indexPathForRowAtPoint:location];
NSLog(@"Swipe detected at %d", selectedIndexPath.row);
ModelObject *rowData = (ModelObject *)[modelArr objectAtIndex:selectedIndexPath.row];
rowData.isAlternateView = YES;

for (int i=0; i<[tempArr count]; i++) {
    if (i!=selectedIndexPath.row) {
        ModelObject *rowToBeCleared = (ModelObject *) [modelArr objectAtIndex:i];
        if ([rowToBeCleared isAlternateView]) {
            [rowToBeCleared setIsAlternateView:NO];
            [tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:[NSIndexPath indexPathForRow:i inSection:0],nil] withRowAnimation:UITableViewRowAnimationLeft];
        }
    }
}

[tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:selectedIndexPath,nil] withRowAnimation:UITableViewRowAnimationRight];
}

1 Ответ

10 голосов
/ 10 ноября 2010

Во-первых, вместо того, чтобы добавлять распознаватель жестов в каждую ячейку, я бы предложил добавить только один распознаватель жестов ко всему представлению , которое содержит табличное представление (или, если это UITableViewController, тогда они 'то же самое).

В viewDidLoad:

UISwipeGestureRecognizer *recognizer = [[UISwipeGestureRecognizer alloc] 
    initWithTarget:self action:@selector(handleSwipe:)];
[recognizer setDirection:(UISwipeGestureRecognizerDirectionRight)];
[self.view addGestureRecognizer:recognizer];
[recognizer release];

Затем в методе handleSwipe:

- (void)handleSwipe:(UISwipeGestureRecognizer *) recognizer
{
    //might need to check if swipe has ended (otherwise not time to handle yet)
    if (recognizer.state != UIGestureRecognizerStateEnded)
        return;

    CGPoint location = [recognizer locationInView:tableView]; //not self.view  
    NSIndexPath *selectedIndexPath = [tableView indexPathForRowAtPoint:location];

    if (selectedIndexPath != nil)
    {
        //user swiped on a tableview cell
    }
    else
    {
        //user did not swipe on a tableview cell
    }
}
...