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

iOS 键盘遮挡输入框解决方案

2016-12-21 14:30 549 查看
//
方法一

- (void)addNotification {

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

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

}

- (void)keyboardWillShow:(NSNotification *)info {

   
CGRect keyboardBounds = [[[infouserInfo]
objectForKey:UIKeyboardFrameEndUserInfoKey]CGRectValue];

    float f =  keyboardBounds.size.height;

   
self.view.frame =CGRectMake(0,0,f,
0);

    

}

- (void)keyboardWillHide:(NSNotification *)info {

   
self.view.frame =CGRectMake(self.view.frame.size.height,0,
0,0);

}

//
方法二

//
开始编辑输入弹出键盘

- (void)textFieldDidBeginEditing:(UITextField *)textField {

    CGRect frame = textField.frame;

    int offset = frame.origin.y
+ 32 - (self.view.frame.size.height
- 216.0);//键盘高度216

    

    NSTimeInterval animationDuration =
0.30f;

    [UIView
beginAnimations:@"ResizeForKeyboard"
context:nil];

    [UIView
setAnimationDuration:animationDuration];

    

   
//将视图的Y坐标向上移动offset个单位,以使下面腾出地方用于软键盘的显示

    if(offset >
0)

       
self.view.frame =
CGRectMake(0.0f, -offset,
self.view.frame.size.width,
self.view.frame.size.height);

    

    [UIView
commitAnimations];

}

//
当用户按下return键收回键盘

- (BOOL)textFieldShouldReturn:(UITextField *)textField {

    [textField
resignFirstResponder];

   
return YES;

}

//
输入框编辑完成后,将视图恢复到原始状态

- (void)textFieldDidEndEditing:(UITextField *)textField {

   
self.view.frame =CGRectMake(0,
0, self.view.frame.size.width,
self.view.frame.size.height);

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