转自:http://www.ithao123.cn/content-9982085.html
一、判断键盘弹出和隐藏状态
1、首先在.h 中定义属性: keyBoardlsVisible 键盘的状态,键盘弹出其值为 YES ,键盘隐藏为NO,可通过状态的值进行自己相应的操作
@property(nonatomic,assign) BOOL keyBoardlsVisible;
2、.m 中定义两个监测键盘状态的通知:keyboardDidShow、keyboardDidHide两个键盘状态的方法。通过这两个方法来知道键盘的状态,并把_keyBoardlsVisible 的值设置为相应的值
NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
[center addObserver:self selector:@selector(keyboardDidShow) name:UIKeyboardDidShowNotification object:nil];
[center addObserver:self selector:@selector(keyboardDidHide) name:UIKeyboardWillHideNotification object:nil];
// 给 _keyBoardlsVisible 赋初值
_keyBoardlsVisible = NO;
3、实现 keyboardDidShow和keyboardDidHide 两个方法
// 键盘弹出触发该方法
- (void)keyboardDidShow
{
NSLog(@"键盘弹出");
_keyBoardlsVisible =YES;
}
// 键盘隐藏触发该方法
- (void)keyboardDidHide
{
NSLog(@"键盘隐藏");
_keyBoardlsVisible =NO;
}
4. 在dealloc中删除通知
- (void)dealloc
{
[[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardDidShowNotification object:nil];
[[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardDidHideNotification object:nil];
}
二、ios代码控制收起键盘
收起键盘一般让控件放弃第一响应就可以了resignFirstResponder,但要在何时让控件调用resignFirstResponder是比较麻烦的,需要具体问题具体分析,以下给几个通用例子,但不全。
#pragma mark - UIResponder override
/* 当一个或多个手指离开屏幕时,发送touchesEnded:withEvent:消息,该消息会被tableView截获 */
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
// if (![_inputTextField isExclusiveTouch]) {
// [_inputTextField resignFirstResponder];
// }
if(bKeyBoardHide == NO)
{
[_inputTextField resignFirstResponder];
}
}
#pragma mark - UITextFiledDelegate
self.textField.delegate=self;
// 点击键盘上的换行符时会调用
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
[textField resignFirstResponder];
return YES;
}
更多的收起方式参考:http://www.open-open.com/code/view/1421812048906