Skip to content

Instantly share code, notes, and snippets.

@ruandao
Last active January 22, 2016 09:56
Show Gist options
  • Save ruandao/9429305 to your computer and use it in GitHub Desktop.
Save ruandao/9429305 to your computer and use it in GitHub Desktop.
用来处理 uitextview 编辑时,键盘挡住输入框的, 这个会将整个frame 上移
// 注意,如果输入的是汉字的话,输入拼音后,会出现新的一行,让你选择拼音所对应的汉字,这个也会触发UIKeyboardWillShowNotification
// 所以,你要加个变量,来判断键盘是否消失,没消失的话就不在上移界面
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view.
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(keyboardWillShow:)
name:UIKeyboardWillShowNotification
object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(keyboardWillHide:)
name:UIKeyboardWillHideNotification
object:nil];
}
#pragma mark keyboard show hide
- (UIView *)findViewThatIsFirstResponder
{
if (self.view.isFirstResponder) {
return self.view;
}
for (UIView *subView in self.view.subviews) {
if ([subView isFirstResponder]) {
return subView;
}
}
return nil;
}
- (void)keyboardWillShow:(NSNotification *)aNotification
{
if (!self.wasKeyboardDidShow) {
NSTimeInterval animationDuration =
[[[aNotification userInfo] objectForKey:UIKeyboardAnimationDurationUserInfoKey] doubleValue];
CGRect frame = self.view.frame;
// frame.origin.y -= 160;
UIView *respView = [self findViewThatIsFirstResponder];
if (respView.frame.origin.y + respView.frame.size.height > frame.size.height-160) {
frame.origin.y -= respView.frame.origin.y + respView.frame.size.height - frame.size.height + 180;
}
[UIView beginAnimations:@"ResizeForKeyboard" context:nil];
[UIView setAnimationDuration:animationDuration];
self.view.frame = frame;
[UIView commitAnimations];
self.wasKeyboardDidShow = YES;
}
}
- (void)keyboardWillHide:(NSNotification *)aNotification
{
NSTimeInterval animationDuration =
[[[aNotification userInfo] objectForKey:UIKeyboardAnimationDurationUserInfoKey] doubleValue];
CGRect frame = self.view.frame;
frame.origin.y = 0;
[UIView beginAnimations:@"ResizeForKeyboard" context:nil];
[UIView setAnimationDuration:animationDuration];
self.view.frame = frame;
[UIView commitAnimations];
self.wasKeyboardDidShow = NO;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment