当键盘弹起的时候,屏幕适配键盘高度的方法

来源:互联网 发布:黄金白银套利软件 编辑:程序博客网 时间:2024/06/04 18:42

当我们使用TextFiled或者TextView的时候,经常会因为键盘弹起而挡住编辑区域,而中文键盘因为拼音的缘故会两次调用keyboardWillShow的监听,现在我贴出一个我自己理解的方式

[objc] view plaincopyprint?在CODE上查看代码片派生到我的代码片
  1. <span style="font-size:18px;">  
  2. - (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil  
  3. {  
  4.     self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];  
  5.     if (self) {  
  6.         // Custom initialization  
  7.         //加入监听  
  8.         [[NSNotificationCenter defaultCenter] addObserver:self  
  9.                                                  selector:@selector(keyboardWillShow:)  
  10.                                                      name:UIKeyboardWillShowNotification  
  11.                                                    object:nil];  
  12.           
  13.         [[NSNotificationCenter defaultCenter] addObserver:self  
  14.                                                  selector:@selector(keyboardWillHide:)  
  15.                                                      name:UIKeyboardWillHideNotification  
  16.                                                    object:nil];  
  17.   
  18.           
  19.     }  
  20.     return self;  
  21. }</span>  

[objc] view plaincopyprint?在CODE上查看代码片派生到我的代码片
  1. <span style="font-size:18px;">  
  2. @property (nonatomic,assign)CGRect              tableViewRect;//设置一个rect来保存你想要升高的view的rect</span>  

[objc] view plaincopyprint?在CODE上查看代码片派生到我的代码片
  1. <span style="font-size:18px;">- (void)keyboardWillShow:(NSNotification *)notif {  
  2.     self.keyBoardRect = [[notif.userInfo objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue];  
  3.           
  4.         [UIView animateWithDuration:0.5 animations:^{  
  5.             CGRect tbRect = self.tableViewRect;  
  6.             tbRect.origin.y -=self.keyBoardRect.size.height;  
  7.             self.tableView.frame = tbRect;  
  8.         } completion:^(BOOL finish){  
  9.               
  10.         }];  
  11.       
  12. }  
  13.   
  14. - (void)keyboardWillHide:(NSNotification *)notif {  
  15.       
  16.         [UIView animateWithDuration:0.5 animations:^{  
  17.               
  18.             self.tableView.frame = self.tableViewRect;  
  19.         } completion:^(BOOL finish){  
  20.               
  21.         }];  
  22.       
  23. }</span>  


用一个临时变量来做一个中转,这样就省去了很多复杂的逻辑,这样就算是中文2次弹起,也不会受任何影响
0 0
原创粉丝点击