(后面有代码)类似于QQ、微信的聊天界面都有一个自定义的toolBar负责输入和各种功能
类似这样的都是需要自定义一个UIView负责完成各个控件的组合。那么问题来了,当输入时,键盘弹出,自定义view的frame就要发生相应的改变,下面就来聊聊键盘监听。
对于键盘的监听一般用到的都是NSNotificationCenter(通知中心),以下是注册一个通知中心,对于键盘变化的事件标志有UIKeyboardWillShowNotification、UIKeyboardWillHideNotification、UIKeyboardWillChangeFrameNotification等一些比较常用的,我本人在这个例子中使用的是UIKeyboardWillChangeFrameNotification(第三种),这种方法是监听键盘发生变化时做出反应,相对于前面两种会更通用。
[[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(keyBoardWillChangeWithNotification:) name:UIKeyboardWillChangeFrameNotification object:nil];
在通知的执行方法里通过通知中心的Info获取frame
- (void)keyBoardWillChangeWithNotification:(NSNotification *)noti
{
NSDictionary *keyBoardInfo = [noti userInfo];
//通知中心根据keyboard的变化拿到frame转化成rect
CGRect keyBoardFrame = [[keyBoardInfo objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue];
//计算出keyboard弹出时间:0.25
CGFloat keyBoardAnimation = [[keyBoardInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey]floatValue];
[UIView animateWithDuration:keyBoardAnimation animations:^{
if (keyBoardFrame.origin.y > self.view.frame.size.height) {
//键盘没出来
self.inputToolBar.y = keyBoardFrame.origin.y - self.inputToolBar.frame.size.height;
}else{
//键盘出来
self.inputToolBar.y = keyBoardFrame.origin.y - self.inputToolBar.frame.size.height;
}
}];
}
以上是自定义view时对键盘的监听。
下面是在使用UITextView和UITextField的时候,通过inputAccessoryView属性给输入时呼出的键盘加一个附属视图(一般为UIToolbar),inputView给一个输入方式,如果不是UITextView或UITextField,inputAccessoryView和inputView为readonly的。
/**
demo 里的这个ViewController主要是为了介绍textView和textField的inputView和inputAccessView的自定义样式
inputAccessView继承与UIView 一般我们都给将一个UIToolbar (工具栏)
inputView则是输入方式,可以是系统给的键盘输入,也可以是自己给定的一种输入方式
当键盘回收时,inputAccessView 和 inputView 都会消失
*/
// UIToolBar 的 items 放的都是 UIBarButtonItem
UIToolbar *toolBar = [[UIToolbar alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 40)];
UIBarButtonItem *cancelBarButton = [[UIBarButtonItem alloc]initWithTitle:@"取消" style:UIBarButtonItemStylePlain target:self action:@selector(cancelBarButtonEvents)];
cancelBarButton.tintColor = [UIColor redColor];
UIBarButtonItem *spaceBarButton = [[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:self action:nil];// 用来布局对齐
UIBarButtonItem *doBarButton = [[UIBarButtonItem alloc]initWithTitle:@"完成" style:UIBarButtonItemStylePlain target:self action:@selector(doBarButtonEvents)];
doBarButton.tintColor = [UIColor orangeColor];
toolBar.items = @[cancelBarButton,spaceBarButton,doBarButton];
//在键盘输入位置的View样式
UIPickerView *pickerView = [[UIPickerView alloc]init];
pickerView.delegate = self;
pickerView.dataSource = self;
//输入方式
self.textView.inputView = pickerView;
// 在键盘上的工具条
self.textView.inputAccessoryView = toolBar;
以上两种方式在开发过程中还是比较常用的,尤其是IM在后面会附上代码,方便查阅