获取键盘高度的实现

        在开发过程中,可能会遇到这样的问题,页面中有textView或者textField,且放置在屏幕的下方,当点击它们进行输入时,发现它们会被键盘挡住,导致用户看不见自己输入的内容,如图所示:


这种效果显然是需要改进的。那么如何能让用户看见自己的输入内容呢?解决方法如下:

1.监听键盘

在.m文件中的viewDidLoad方法中添加监听

    [[NSNotificationCenterdefaultCenter] addObserver:selfselector:@selector(keyboardWillShow:)name:UIKeyboardWillShowNotificationobject:nil];

    [[NSNotificationCenterdefaultCenter] addObserver:selfselector:@selector(keyboardWillHide:)name:UIKeyboardWillHideNotificationobject:nil];

//配置Iphone5的

#ifdef __IPHONE_5_0

    float version = [[[UIDevicecurrentDevice] systemVersion] floatValue];

    if (version >= 5.0) {

        [[NSNotificationCenterdefaultCenter] addObserver:selfselector:@selector(keyboardWillShow:)name:UIKeyboardWillChangeFrameNotificationobject:nil];

    }

#endif

2.获取键盘的高度

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

    NSDictionary *info = [notification userInfo];

    float i= [[infoobjectForKey:UIKeyboardFrameEndUserInfoKey]CGRectValue].size.height;//得到键盘的高度

    [selfletViewUp:i];//让当前屏幕抬高

}

//抬高当前屏幕

- (void)letViewUp:(float) h{

self.view.frame=CGRectMake(self.view.frame.origin.x,-h, self.view.frame.size.width,self.view.frame.size.height);

}

效果图如下:

此时屏幕被抬高,用户可以看见自己输入的内容

//恢复屏幕高度,当输入完成以后一定不要忘了恢复键盘的高度

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

    [selftableViewDown];

    

}

- (void)tableViewDown{

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

}

再次要添加个让键盘消失的方法,否则键盘不会下来

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{

    [textFieldresignFirstResponder];

}

效果图如下:

此时屏幕又回到原来的高度












  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值