简体   繁体   English

selectRowAtIndexPath不会滚动到UITableView中的正确位置

[英]selectRowAtIndexPath does not scroll in to the correct position in UITableView

Im having around 80 items. 我有大约80项。 if my selected index was 15(or less value) it scrolls to the correct position. 如果我选择的索引是15(或更小的值),它会滚动到正确的位置。 But if selection index was 70 it does not scroll. 但如果选择指数为70,则不会滚动。 but it has selected the row when i manually scroll. 但它在我手动滚动时选择了该行。 Does anyone has idea how to fix that? 有谁知道如何解决这个问题?

-(void)select:(NSString*)selectedIndex {
    if(selectedIndex == nil){
        return;
    }
    UITableView *tableView = (UITableView*)view;
    if(tableView == nil) {
        return;
    }

    NSIndexPath *nextIndexPath = [self findIndexPath:selectedIndex table:tableView];

    if(nextIndexPath != nil && ![viewController isSelectable:[selectedIndex intValue]]){
        NSArray *indexPaths = [tableView indexPathsForVisibleRows];
        nextIndexPath = [self nextMoveUp:nextIndexPath :indexPaths];
    }
    if(nextIndexPath != nil) {
        [tableView selectRowAtIndexPath:nextIndexPath animated:YES scrollPosition:UITableViewScrollPositionMiddle];
        if ([tableView cellForRowAtIndexPath:nextIndexPath] == nil) {
            // cell is not visible - scroll it into view
            [tableView scrollToRowAtIndexPath:nextIndexPath atScrollPosition:UITableViewScrollPositionNone animated:YES];
        }
    }
}

-(NSIndexPath*)findIndexPath:(NSString*)selectedIndex table:(UITableView*)tableView{
    NSArray *indexPaths = [tableView indexPathsForVisibleRows];
    if(indexPaths == nil || [indexPaths count] == 0) {
        return nil;
    }
    NSIndexPath *lastIndexPath = NULL;
    for (NSIndexPath *path in indexPaths) {
        if(path.row == [selectedIndex intValue]){
            return path;
        }
        lastIndexPath = path;
    }
    if(lastIndexPath != nil && lastIndexPath.row < [selectedIndex intValue]){
        [tableView scrollToRowAtIndexPath:lastIndexPath atScrollPosition:UITableViewScrollPositionTop animated:NO];
        return [self findIndexPath:selectedIndex table:tableView];
    }
    return nil;
}

I just had this problem. 我刚遇到这个问题。 In my case I was calling scrollToRowAtIndexPath (or selectRowAtIndexPath) before all the rows were defined, ie before cellForRowAtIndexPath had been called on all the rows. 在我的情况下,我在定义所有行之前调用scrollToRowAtIndexPath(或selectRowAtIndexPath),即在所有行上调用cellForRowAtIndexPath之前。 My solution was to define a method to select the row and call it with performSelectorOnMainThread to delay until the first refresh was complete. 我的解决方案是定义一个方法来选择行并使用performSelectorOnMainThread调用它来延迟直到第一次刷新完成。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM