Skip to content

Instantly share code, notes, and snippets.

@hsavit1
Last active August 29, 2015 14:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hsavit1/2191ef3e368994fba346 to your computer and use it in GitHub Desktop.
Save hsavit1/2191ef3e368994fba346 to your computer and use it in GitHub Desktop.
Shift Keyboard if Necessary (login view)
- (void)shiftKeyboardIfNecessary {
CGRect viewFrame = self.view.frame;
CGRect activeTextFieldFrame = self.activeTextField.frame;
CGFloat bottomPadding = 4;
// The lowest point visible on the screen is the height of the screen minus the height of the keyboard, then adjusted by the current position
// of the view. So, if the view has already been shifted upwards (negative origin), then more of the lower part of the screen is visible.
CGFloat lowestPointCoveredByKeyboard = -viewFrame.origin.y + viewFrame.size.height - self.keyboardFrame.size.height;
// The active text field's lowest point is its origin.y + its height (so, if it was at y=200, and is 21px tall, then the lowest point is 221.
// We then check the lowest point covered by the keyboard, as described above, and check if we're below that (and if so, by how much). This
// will be the amount (plus a little padding) that we further offset the view by.
CGFloat distanceActiveTextFieldIsUnderFrame = activeTextFieldFrame.origin.y + activeTextFieldFrame.size.height - lowestPointCoveredByKeyboard;
if (distanceActiveTextFieldIsUnderFrame > 0) {
viewFrame.origin.y -= distanceActiveTextFieldIsUnderFrame + bottomPadding;
self.view.frame = viewFrame;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment