您的位置:首页 > 其它

避免键盘挡住输入框常用的两个通知方法

2016-08-23 15:28 405 查看
两个监听键盘显示和消失的通知

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];


当键盘状态改变的时候,键盘位置调整(或键盘所在的父view位置调整)

#pragma mark - keyboard
-(void) keyboardWillShow:(NSNotification *)note
{
// get keyboard size and loctaion
CGRect keyboardBounds;
[[note.userInfo valueForKey:UIKeyboardFrameEndUserInfoKey] getValue: &keyboardBounds];
NSNumber *duration = [note.userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey];
NSNumber *curve = [note.userInfo objectForKey:UIKeyboardAnimationCurveUserInfoKey];

// Need to translate the bounds to account for rotation.
keyboardBounds = [self convertRect:keyboardBounds toView:nil];

// get a rect for the textView frame
CGRect containerFrame = _contentView.frame;
containerFrame.origin.y = CGRectGetHeight(_backgroundMarkView.frame) - (keyboardBounds.size.height + containerFrame.size.height);
// animations settings

[UIView beginAnimations:nil context:NULL];
[UIView setAnimationBeginsFromCurrentState:YES];
[UIView setAnimationDuration:[duration doubleValue]];
[UIView setAnimationCurve:[curve intValue]];

// set views with new info
_contentView.frame = containerFrame;

// commit animations
[UIView commitAnimations];
}

-(void) keyboardWillHide:(NSNotification *)note
{
NSNumber *duration = [note.userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey];
NSNumber *curve = [note.userInfo objectForKey:UIKeyboardAnimationCurveUserInfoKey];

// animations settings
[UIView beginAnimations:nil context:NULL];
[UIView setAnimationBeginsFromCurrentState:YES];
[UIView setAnimationDuration:[duration doubleValue]];
[UIView setAnimationCurve:[curve intValue]];

// set views with new info
_contentView.center = _backgroundMarkView.center;

// commit animations
[UIView commitAnimations];
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  键盘keyboard