在viewWillAppear中注册键盘通知,在viewWillDisappear中删除键盘通知,以避免view在后台时响应通知进行不必要的操作。
另外,书中提到,有很多其他方法比如使用UITextField的代理事件来进行操作,应该避免使用,因为用户有可能使用蓝牙或其他外设进行输入,此时没有软键盘,有可能造成界面显示的问题。
- (void)viewWillAppear:(BOOL)animated
{
// Custom initialization
//注册键盘弹起与收起通知
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(keyboardDidShow:)
name:UIKeyboardDidShowNotification
object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(keyboardDidHide:)
name:UIKeyboardDidHideNotification
object:nil];
}删除响应
- (void)viewWillDisappear:(BOOL)animated
{
[[NSNotificationCenter defaultCenter] removeObserver:self];
}-(void)keyboardDidShow:(NSNotification *)note
{
NSDictionary *info = [note userInfo];
CGSize keyboardSize = [[info objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue].size;
self.keybordHeight = keyboardSize.height;
//自适应代码(输入法改变也可随之改变)
[UIView beginAnimations:nil context:NULL];//此处添加动画,使之变化平滑一点
[UIView setAnimationDuration:0.3];
[UIView commitAnimations];
}-(void)keyboardDidHide:(NSNotification *)note
{
//还原
[UIView beginAnimations:nil context:NULL];//此处添加动画,使之变化平滑一点
[UIView setAnimationDuration:0.3];
[UIView commitAnimations];
}推荐使用第三方类库
IQKeyboardManager
本文介绍如何在iOS应用中正确地使用键盘通知来调整界面布局,包括注册和注销通知的方法,并建议使用第三方库IQKeyboardManager来简化流程。
4495

被折叠的 条评论
为什么被折叠?



