iOS软键盘遮挡元素时得处理办法

来源:互联网 发布:数据库与管理信息系统 编辑:程序博客网 时间:2024/06/05 04:32

  这几天在写自己的iOS项目时候遇到了问题:

当软键盘没有弹起时,页面看起来还比较正常。当点击了text field时,软键盘弹出,就有将text field遮挡的风险

               

在网上查阅了一些资料之后,自己做了下总结:

1.在对应view的controller的.h文件中添加<UITextFieldDelegate>

#import <UIKit/UIKit.h>@interface WYILoginViewController : UIViewController<UITextFieldDelegate>@end
后来测试将<UITextFieldDelegate>删除,发现也没有报错,只是后面有警告


2.在controller的实现文件的viewDidLoad方法中增加:

- (void)viewDidLoad{    [super viewDidLoad];    self.emailTextField.delegate = self;}

注:emailTextField是页面text field通过拖拽生成的outlet变量

这句很重要,如果不写这句后面的实现的UITextFieldDelegate的方法都无法执行;其次,第1步的<UITextFieldDelegate>如果不写,这里会警告。


3.实现UITextFieldDelegate

-(void)textFieldDidBeginEditing:(UITextField *)textField{    NSTimeInterval animationDuration = 0.20f;    [UIView beginAnimations:@"ResizeForKeyboard" context:nil];    [UIView setAnimationDuration:animationDuration];    self.view.frame = CGRectMake(0.0f, -kOFFSET_FOR_KEYBOARD, self.view.frame.size.width, self.view.frame.size.height);    [UIView commitAnimations];}-(BOOL)textFieldShouldReturn:(UITextField *)textField{    [self.emailTextField resignFirstResponder];    return YES;}-(void)textFieldDidEndEditing:(UITextField *)textField{    NSTimeInterval animationDuration = 0.2f;    [UIView beginAnimations:@"ResizeForKeyboard" context:nil];    [UIView setAnimationDuration:animationDuration];    self.view.frame = CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height);    [UIView commitAnimations];}

注:kOFFSET_FOR_KEYBOARD 我在头部做过声明:

         #define kOFFSET_FOR_KEYBOARD 150.0

这个高度是键盘弹起的高度,从网上查来的。


4.添加点击背景,键盘消失的方法:

- (IBAction)backgroundTap:(id)sender {    [self.view endEditing:YES];}

这步要注意在storyboard中将view的Custom Class->Class改成UIControl,并拖拽到backgroundTap方法:




最后执行之后:

页面整体网上移动了150px,也可以根据自己的实际需求,改变上升的高度。

当然,我是为了做个备忘,如果有写错的地方,大家可以留言告知。

  更多精彩请关注微信公众号:兔贩子



0 0
原创粉丝点击