IOS之监听键盘打开和关闭
使用广播通知,在viewWillAppear时注册键盘打开和关闭的事件监听,在viewWilldisappear时解除键盘打开和关闭的事件监听。请注意viewWillAppear和viewWilldisappears事件触发的时机。
在ViewController.m中添加如下四个方法。
-(void) viewWillAppear:(BOOL)animated { NSLog(@"viewWillAppear:在ViewController初始化之后,进入活动状态之前"); //注册键盘出现通知 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector (keyboardShow:) name: UIKeyboardDidShowNotification object:nil]; //注册键盘隐藏通知 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector (keyboardHide:) name: UIKeyboardDidHideNotification object:nil]; [super viewWillAppear:animated]; } -(void) viewWillDisappear:(BOOL)animated { NSLog(@"viewWillDisappear:在ViewControler终止或进入后台之前");</span> //解除键盘出现通知 [[NSNotificationCenter defaultCenter] removeObserver:self name: UIKeyboardDidShowNotification object:nil]; //解除键盘隐藏通知 [[NSNotificationCenter defaultCenter] removeObserver:self name: UIKeyboardDidHideNotification object:nil]; [super viewWillDisappear:animated]; } //自定义键盘打开时触发的事件 -(void) keyboardShow: (NSNotification *)notif { NSLog(@"keyboardShow键盘打开"); } //自定义键盘关闭时触发的事件 -(void) keyboardHide: (NSNotification *)notif { NSLog(@"keyboardHide键盘关闭"); }
相关推荐
我的iOS王者之路 2019-06-26
wuxiaohui0 2014-06-13
qianchunqiang 2014-04-23
dahuichen 2013-07-12
IOSPanPan 2013-03-18
iOS开发分享交流 2013-01-04
suweierxing 2016-11-18
知更鸟CoolLee 2016-08-11
我爱编程 2011-07-22
iosWorker 2011-05-31
石虎 2011-03-01
前端外刊评论 2017-12-19