Skip to content

Instantly share code, notes, and snippets.

@derekli66
Last active June 16, 2018 01:30
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 derekli66/0fc59cfba32461e98725bbf73068bee9 to your computer and use it in GitHub Desktop.
Save derekli66/0fc59cfba32461e98725bbf73068bee9 to your computer and use it in GitHub Desktop.
Make UIScrollView go upward when the contained UITextField or UITextView becomes first responder.
#pragma mark - Keyboard Notifications
- (void)keyboardDisappeared:(NSNotification*)notification
{
self.scrollView.contentInset = UIEdgeInsetsZero;
[self.scrollView setContentOffset:CGPointMake(0.0, 0.0) animated:YES];
}
- (void)KeyboardWillChangeFrame:(NSNotification*)notification
{
NSDictionary *keyboardInfo = [notification userInfo];
NSValue *keyboardFrameBegin = [keyboardInfo valueForKey:UIKeyboardFrameEndUserInfoKey];
CGRect keyboardFrame = [keyboardFrameBegin CGRectValue];
self.scrollView.contentInset = UIEdgeInsetsMake(0.0f, 0.0f, keyboardFrame.size.height, 0.0f);
[self.scrollView setContentOffset:CGPointMake(0.0, keyboardFrame.size.height/2) animated:YES];
}
@derekli66
Copy link
Author

[self.scrollView setContentOffset:CGPointMake(0.0, 0.0) animated:YES];

and

[self.scrollView setContentOffset:CGPointMake(0.0, keyboardFrame.size.height/2) animated:YES];

may not fit in your case.

If you find the editing position from ScrollView is too high after setContentOffset. Then, remove these two lines.

I have not checked the behavior when applying on UITableView. But, basically, make contentInset changed is necessary.

@derekli66
Copy link
Author

Another way to set correct content offset is to get current first responder and set the content offset accordingly. About how to get current responder, you could refer to UIView+FirstResponder.swift

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment