Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change UITableView's contentInset without changing its contentOffset?

I want to create a UI similar to Apple's Messages app on the iPhone. I have a table view and a text field below it. When I select the text field, I animate the table view's contentInset as the keyboard slides up so that the content is shown above the keyboard.

I have some code that uses a pan gesture recognizer to detect when the user is scrolling down the table view and animate the keyboard down as this happens (if you see Apple's Messages app, it has the same functionality to dismiss the keyboard. You scroll down on the table view and as your finger slides past the text field the keyboard goes down with it).

This works great, but if the table view is scrolled to the top and I start changing its content inset as the keyboard slides down, the table view scrolls past the top and then snaps back to the top causing a weird jerky animation. I figure this is because changing the contentInset resets the contentOffset to the top of the table view if the table view is scrolled past the top, and this is making it act strange.

Does anyone know how to change the contentInset of a scroll view without changing its contentOffset?

like image 727
Anshu Chimala Avatar asked Jul 17 '12 04:07

Anshu Chimala


1 Answers

I managed to get everything to work perfectly with a small workaround. I just did this:

// in a method that gets repeatedly called as the pan gesture recognizer changes
if([tableView contentOffset].y > 0) {
    UIEdgeInsets insets = [tableView contentInsets];
    inset.bottom = currentKeyboardHeight;
    [tableView setContentInset:inset];
}

so that the insets wouldn't be changed if the contentOffset was at the very top or scrolled past the top. If the table is scrolled down a bit and dragged, it'll change the insets until it hits the top, then it stops changing them so that the weird flickering doesn't occur.


Edit: Figured out the underlying cause and thought I'd update this rather than just leave the workaround. What I was doing was mixing a CGAffineTransformMakeTranslation in the middle of my frame computations, which is a big no-no according to Apple documentation. When the transform property is not CGAffineTransformIdentity, the frame becomes undefined, and this caused some very strange behavior if I scrolled the table view around and changed its content insets at the same time.

like image 56
Anshu Chimala Avatar answered Sep 22 '22 03:09

Anshu Chimala