Force UITableView to Scroll to Tops of Cells

后端 未结 6 2022
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-29 13:41

Is there a way to make UITableViews scroll cell to cell? That is, the top of the Table View is always the top of a UITableViewCell.

I tried the pageation flag, but t

6条回答
  •  隐瞒了意图╮
    2020-12-29 14:02

    This approach handles a table view with varying row heights. It assumes the table view has a single section.

    - (void)scrollViewWillEndDragging:(UIScrollView *)scrollView
                         withVelocity:(CGPoint)velocity
                  targetContentOffset:(inout CGPoint *)targetContentOffset {
    
        // Find the row where the animation will currently end.
        NSInteger targetRow = [[self.tableView indexPathForRowAtPoint:*targetContentOffset] row];
    
        // Tell the animation to end at the top of that row.
        *targetContentOffset = [self offsetForTopOfRow:targetRow];
    }
    

    The offset is calculated by this helper method, which sums the heights of all rows above the target row.

    - (CGPoint)offsetForTopOfRow:(NSInteger)row {
    
        CGPoint offset = CGPointZero;
    
        for (int i = 0; i < row; i++) {
            NSIndexPath *indexPath = [NSIndexPath indexPathForRow:i inSection:0];
            CGFloat height = [self.tableView.delegate tableView:self.tableView heightForRowAtIndexPath:indexPath];
            offset.y += height;
        }
    
        return offset;
    }
    

提交回复
热议问题