前面写过一篇关于自定义toolbar的博客,于是联想到键盘上方的弹出的自定义toolbar。根据键盘状态toolbar显示不同位置。
// 一般用在自定义UITextView中,例如微博的发微博或者意见反馈等
UITextView *field = [[UITextView alloc]init];
field.frame = CGRectMake((self.view.size.width - 300) / 2, 30, 300, 100);
field.backgroundColor = [UIColor redColor];
field.alwaysBounceVertical = YES;
// 成为第一相应者 就能叫出键盘 设置代理就是为了拖动textView的时候键盘退出
field.delegate = self;
[self.view addSubview:field];
self.field = field;
监听键盘的状态,根据键盘状态触发不同的方法
[[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
[[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
自定义toolbar在控制器刚出现的时候会出现在控制器底部。而不是根据键盘的消失而消失。
如果是跟着键盘一块消失就用一下方法,但是监听就用不到了。
// field.inputAccessoryView = toolbar;
HMStatusToolbar *toolbar = [[HMStatusToolbar alloc]init];
toolbar.width = self.view.size.width;
toolbar.height = 44;
toolbar.y = self.view.height - toolbar.height;
toolbar.delegate = self;
[self.view addSubview:toolbar];
self.toolbar = toolbar;
#pragma mark - 键盘处理
/**
* 键盘即将隐藏
*/
- (void)keyboardWillHide:(NSNotification *)note
{
// 1.键盘弹出需要的时间
CGFloat duration = [note.userInfo[UIKeyboardAnimationDurationUserInfoKey] doubleValue];
// 2.动画
[UIView animateWithDuration:duration animations:^{
self.toolbar.transform = CGAffineTransformIdentity;
}];
}
/**
* 键盘即将弹出
*/
- (void)keyboardWillShow:(NSNotification *)note
{
// 1.键盘弹出需要的时间
CGFloat duration = [note.userInfo[UIKeyboardAnimationDurationUserInfoKey] doubleValue];
// 2.动画
[UIView animateWithDuration:duration animations:^{
// 取出键盘高度
CGRect keyboardF = [note.userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue];
CGFloat keyboardH = keyboardF.size.height;
self.toolbar.transform = CGAffineTransformMakeTranslation(0, - keyboardH);
}];
}
-(void)viewDidAppear:(BOOL)animated {
[super viewDidAppear:animated];
/**
* 让键盘成为第一相应者
*/
[self.field becomeFirstResponder];
}
#pragma mark -- UITextView代理方法
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView {
NSLog(@"开始拖拽");
[self.view endEditing:YES];
}
这样键盘上方的一个自定义toolbar就定义好可以使用了。接下来会介绍富文本。