Last active
June 16, 2018 01:30
-
-
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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]; | |
} |
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
[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.