How to change UITableView content insets only if keyboard covers view?

时间:2015-10-30 22:11:38

标签: ios uitableview

I have a view controller that contains a tableview. I reuse this view controller in multiple places in my app, so that it is inside of a split view controller and also within a popover on iPad.

I added observers to listen for keyboard showing/hiding, and I change my content insets based on the keyboard height. This works whenever the view controller is the full screen height, but it doesn't work in the popover, where the popover resizes and the tableview is not actually covered by the keyboard, leaving me with a bunch of empty space.

Is there a solution for this? How can I only change the content insets if the keyboard covers the view?

1 个答案:

答案 0 :(得分:0)

You just need find how much of your table view the keyboard will cover, and set the inset by that much. /* Get the keyboard rect (which is screen coordinates) in tableView coordinates */ CGRect endFrameScreen = [[note.userInfo objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue]; CGRect endFrameWindow = [tableView.window convertRect:endFrameScreen fromWindow:nil]; CGRect endFrameView = [tableView convertRect:endFrameWindow fromView:nil]; if (!CGRectIntersectsRect(tableView.bounds, endFrameView)) { /* The keyboard will not cover our tableView; nothing to do */ return; } /* This is how much we need to inset */ CGFloat bottomInset = CGRectGetMaxY(tableView.bounds) - endFrameView.origin.y; If using iOS8+ only, the two convertRect steps can be changed to a single one with convertRect:fromCoordinateSpace:[[UIScreen mainScreen] coordinateSpace]