Skip to content

Instantly share code, notes, and snippets.

@derekli66
Last active August 29, 2015 14:19
Show Gist options
  • Save derekli66/412c34418ae78761a562 to your computer and use it in GitHub Desktop.
Save derekli66/412c34418ae78761a562 to your computer and use it in GitHub Desktop.
// 1. Before using following code snippet, make sure to add textfields on a UIScrollView
// 2. The following code snippet will lead the first responder textfield just top of showing keyboard.
// 3. The trick is to set enough scrolling space for scroll view to raise all textfields up.
// When target textfield is touched, the scroll view will do the animation automatically and raise textfields up.
// 4. Do not combine other technique to raise up textfields over keyboard.
- (instancetype)init
{
self = [super init];
if (self) {
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(keyboardDisappeared:)
name:UIKeyboardWillHideNotification
object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(KeyboardWillChangeFrame:)
name:UIKeyboardWillChangeFrameNotification
object:nil];
}
return self;
}
- (void)keyboardDisappeared:(NSNotification*)notification
{
scrollView.contentInset = UIEdgeInsetsZero;
}
- (void)KeyboardWillChangeFrame:(NSNotification*)notification
{
NSDictionary *keyboardInfo = [notification userInfo];
NSValue *keyboardFrameBegin = [keyboardInfo valueForKey:UIKeyboardFrameEndUserInfoKey];
CGRect keyboardFrame = [keyboardFrameBegin CGRectValue];
scrollView.contentInset = UIEdgeInsetsMake(0.0f, 0.0f, keyboardFrame.size.height, 0.0f);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment