您的位置:首页 > 移动开发 > IOS开发

IOS8下利用自动布局实现键盘的弹出效果

2015-01-04 09:46 609 查看
-(void)keyboardChange:(NSNotification*)notice
{
NSValue *value = [[notice userInfo] objectForKey:@"UIKeyboardFrameEndUserInfoKey"];
float keyEnd_y = [value CGRectValue].origin.y;
float animationDuration = [[notice userInfo][@"UIKeyboardAnimationDurationUserInfoKey"] floatValue];

CGRect frame = [[UIScreen mainScreen]bounds];//屏幕尺寸
int SCREEN_WIDTH = frame.size.width;
int SCREEN_HEIGHT = frame.size.height;

if(!shouldResignFirstResponder){
UIView *alphaCoverView = [[[UIApplication sharedApplication].delegate window] viewWithTag:10001];
if (!alphaCoverView) {
alphaCoverView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, keyEnd_y - 40)];
[alphaCoverView setBackgroundColor:[UIColor blackColor]];
alphaCoverView.alpha = 0.0;
alphaCoverView.tag = 10001;
UITapGestureRecognizer *tapToResignirstResponder = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(textFielfWillResignFirstResponder)];
[alphaCoverView addGestureRecognizer:tapToResignirstResponder];
[[[UIApplication sharedApplication].delegate window] addSubview:alphaCoverView];
}
[UIView animateWithDuration:animationDuration animations:^{
alphaCoverView.alpha = 0.4;
alphaCoverView.frame = CGRectMake(0, 0, SCREEN_WIDTH, keyEnd_y - 40);//40是编辑框视图的高
}];
}
float constant = 0.0;
if (shouldResignFirstResponder) {
//收回键盘时,将约束的值复原
constant = SCREEN_HEIGHT - keyEnd_y;
[UIView animateWithDuration:animationDuration animations:^{
_m_spaceToBottom.constant = constant;
[self.view layoutIfNeeded];
}];
shouldResignFirstResponder = NO;
}else{
constant = SCREEN_HEIGHT - keyEnd_y-46;//46是编辑框距离屏幕底部的距离
[UIView animateWithDuration:animationDuration animations:^{
_m_spaceToBottom.constant = constant;
[self.view layoutIfNeeded];
}];
}
}
- (void)textFielfWillResignFirstResponder{
UIView *view = [[[UIApplication sharedApplication].delegate window] viewWithTag:10001];
[view removeFromSuperview];
shouldResignFirstResponder = YES;
[self.view endEditing:YES];
}


//键盘变化监听
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardChange:) name:@"UIKeyboardWillChangeFrameNotification" object:nil];


借鉴文章:
http://blog.csdn.net/u013016828/article/details/42102411
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐