Want UITableView to “snap to cell”

前端 未结 7 1603
长发绾君心
长发绾君心 2020-12-23 17:40

I am displaying fairly large images in a UITableView. As the user scrolls, I\'d like to the table view to always snap the center-most photo in the middle. That

7条回答
  •  失恋的感觉
    2020-12-23 18:23

    Extending @mikepj answer, (which in turn extended the great answer by @JesseRusak), this code lets you snap to a cell, even when cells have a variable (or unknown) height, and will snap to the next row if you'll scroll over the bottom half of the row, making it more "natural".

    Original Swift 4.2 code: (for convenience, this is the actual code I developed and tested)

    func scrollViewWillEndDragging(_ scrollView: UIScrollView, withVelocity velocity: CGPoint, targetContentOffset: UnsafeMutablePointer) {
        guard var scrollingToIP = table.indexPathForRow(at: CGPoint(x: 0, y: targetContentOffset.pointee.y)) else {
            return
        }
        var scrollingToRect = table.rectForRow(at: scrollingToIP)
        let roundingRow = Int(((targetContentOffset.pointee.y - scrollingToRect.origin.y) / scrollingToRect.size.height).rounded())
        scrollingToIP.row += roundingRow
        scrollingToRect = table.rectForRow(at: scrollingToIP)
        targetContentOffset.pointee.y = scrollingToRect.origin.y
    }
    

    (translated) Objective-C code: (since this question is tagged objective-c)

    - (void)scrollViewWillEndDragging:(UIScrollView *)scrollView withVelocity:(CGPoint)velocity targetContentOffset:(inout CGPoint *)targetContentOffset {
        NSIndexPath *scrollingToIP = [self.tableView indexPathForRowAtPoint:CGPointMake(0, targetContentOffset->y)];
        if (scrollingToIP == nil)
            return;
        CGRect scrollingToRect = [table rectForRowAtIndexPath:scrollingToIP];
        NSInteger roundingRow = (NSInteger)(round(targetContentOffset->y - scrollingToRect.origin.y) / scrollingToRect.size.height));
        scrollingToIP.row += roundingRow;
        scrollingToRect = [table rectForRowAtIndexPath:scrollingToIP];
        targetContentOffset->y = scrollingToRect.origin.y;
    }
    

提交回复
热议问题