键盘遮挡控件(textfield/textview.......)

王朝学院·作者佚名  2016-08-27
窄屏简体版  字體: 小  |  中  |  大  |  超大  

采用的是通知的常规方式

//解决键盘遮挡问题

//选择didShow是因为需要键盘的高度

//选择willHide是因为视图frame重置需要优先于键盘消失,否则表现得不连贯

[[NSNotificationCenter defaultCenter] addObserver:self

selector:@selector(keyboardWasShown:)

name:UIKeyboardDidShowNotificationobject:nil];

[[NSNotificationCenter defaultCenter] addObserver:self

selector:@selector(keyboardWasHide:)

name:UIKeyboardWillHideNotificationobject:nil];

触发的方法

-(void)keyboardWasShown:(NSNotification*)notification

{//获取键盘高度NSValue* value=notification.userInfo[UIKeyboardFrameBeginUserInfoKey];

CGFloat keyBoradHeight=[value CGRectValue].size.height;

NSNumber* animationTime=notification.userInfo[UIKeyboardAnimationDurationUserInfoKey];doubletime=[animationTime doubleValue];//获取被遮挡控件距离controller底部的距离floata=self.view4.frame.origin.y+self.view4.frame.size.height;floatb = self.view.frame.size.height-a;if(b<keyBoradHeight)

{//动画效果[UIView animateWithDuration:time

animations:^{//键盘被挡住了CGRect viewCGrect=self.view.frame;//视图应该上移所以是-viewCGrect.origin.y=viewCGrect.origin.y-(keyBoradHeight-b);

[self.view setFrame:viewCGrect];

} completion:nil];

}

}-(void)keyboardWasHide:(NSNotification*)notification

{

NSValue* value=notification.userInfo[UIKeyboardFrameBeginUserInfoKey];

CGFloat keyBoradHeight=[value CGRectValue].size.height;floata=self.view4.frame.origin.y+self.view4.frame.size.height;floatb = self.view.frame.size.height-a;

CGRect viewCGrect=self.view.frame;

viewCGrect.origin.y=viewCGrect.origin.y+(keyBoradHeight-b);

[self.view setFrame:viewCGrect];

}

最后移除通知

-(void)viewWillDisappear:(BOOL)animated

{

[super viewWillDisappear:animated];

[[NSNotificationCenter defaultCenter] removeObserver:self

name:UIKeyboardWillHideNotificationobject:nil];

[[NSNotificationCenter defaultCenter] removeObserver:self

name:UIKeyboardDidShowNotificationobject:nil];

}

最终测试改方式只适用于输入控件比较少的界面,更多的可以使用gitHub上第三方

DaidoujiChen / DaiDodgeKeyboardhackiftekhar / IQKeyboardManager

 
 
免责声明:本文为网络用户发布,其观点仅代表作者个人观点,与本站无关,本站仅提供信息存储服务。文中陈述内容未经本站证实,其真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
 
© 2005- 王朝網路 版權所有 導航