Prevent cell from scrolling out of view

I have a UITableView with multiple screens worth of cells and the height of the cells vary. At a certain point in the user's workflow, I want to prevent a specific cell from being scrolled out of view. I want it to allow it to scroll from the top of the screen to the bottom but not out of view.

I'm trying to solve this by updating the tableView.contentInset property with the following logic...

let visibleContentHeight = tableView.bounds.height
var insetTop = (cell.frame.origin.y - visibleContentHeight)
insetTop = (insetTop < 0) ? 0 : -insetTop
var insetBottom = tableView.contentSize.height - (cell.frame.origin.y + cell.frame.height + visibleContentHeight)
insetBottom = (insetBottom < 0) ? 0 : -insetBottom
tableView.contentInset = UIEdgeInsets(top: insetTop, left: 0, bottom: insetBottom, right: 0)

This doesn't seem to work exactly right. When scrolling, the cell's top/bottom doesn't line up with the view's top/bottom. And the difference between those margins is not consistent.

Printing out some the raw values, it looks like the cell's frame.origin sometimes changes as well as tableView.contentSize.height. I assume the system is using tableView.estimatedRowHeight to calculate the table's content height for the cells that are not loaded, so that's probably another factor.

Is setting contentInset not the way to do this? Is there another way? Is there an error in my math/logic? I must be missing something. Any help is appreciated.

Thanks.

Prevent cell from scrolling out of view
 
 
Q