Swift 3: UITableView snap to cells

Swift 3: UITableView snap to cells

If you have your UITableViews snap to their cells, you’ll end up with a more refined user experience. This solution I have works with cells that are consistent in their height (static). You could always work with dynamic heights if you wanted to.

func scrollViewWillEndDragging(_ scrollView: UIScrollView, withVelocity velocity: CGPoint, targetContentOffset: UnsafeMutablePointer<CGPoint>) {
        if scrollView == suggestionsTableView {
            let cellHeight = CGFloat(60.0)
            let y          = targetContentOffset.pointee.y + scrollView.contentInset.top + (cellHeight / 2)
            let cellIndex  = floor(y / cellHeight)
            targetContentOffset.pointee.y = cellIndex * cellHeight - scrollView.contentInset.top
        }
    }

As you can see cellHeight is a set float value, it’s there where you would want to determine the dynamic height. This little bit of code makes a UITableView a lot more refined as it doesn’t clip cell contents when a user lifts their finger from a drag.

Leave a Reply

Your email address will not be published. Required fields are marked *

Time limit is exhausted. Please reload CAPTCHA.

This site uses Akismet to reduce spam. Learn how your comment data is processed.