动态获取iphone键盘的高度

本文介绍如何在iOS应用中监听键盘的显示与隐藏事件,并根据键盘高度进行界面自适应调整的方法。通过注册通知中心的观察者,可以捕获到键盘将要显示的通知并获取键盘的高度,进而实现界面元素的位置调整。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

监听键盘呼出事件的消息:


[plain]  view plain copy
  1. [[NSNotificationCenter defaultCenter] addObserver:self   
  2.                                          selector:@selector(keyboardWillShow:)   
  3.                                              name:UIKeyboardWillShowNotification   
  4.                                            object:nil];  

针对键盘高度做出自适应:

 

 

[plain]  view plain copy
  1. (void)keyboardWillShow:(NSNotification *)notification    
  2.    
  3.     static CGFloat normalKeyboardHeight 216.0f;  //iphone键盘  
  4.     NSDictionary *info [notification userInfo];    
  5.     CGSize kbSize [[info objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue].size;       
  6.     CGFloat distanceToMove kbSize.height normalKeyboardHeight;    
  7.         
  8.     //自适应代码    
  9.  
最后,移除观察者。


写了个小例子:

猛戳这里获取Demo




 

 
NSNotificationCenter *defaultCenter = [NSNotificationCenter defaultCenter];
      //UIKeyboardWillShowNotifi cation键盘出现
      [defaultCenter addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotifi cation object:nil];
 
      //UIKeyboardWillHideNotifi cation 键盘隐藏
      [defaultCenter addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotifi cation object:nil];
 
- (void)keyboardWillShow:(NSNotification *)aNotification
{
      //获取键盘的高度
NSDictionary *userInfo = [aNotification userInfo];
      NSValue *aValue = [userInfo objectForKey:UIKeyboardFrameEndUserIn foKey];
      CGRect keyboardRect = [aValue CGRectValue];
      int height = keyboardRect.size.width;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值