inputAccessoryView : 系统自带的键盘上面的工具条视图(并无什么卵用)git
因为系统自带的工具条随着键盘的隐藏也一块儿隐藏了,而如今不少应用的需求的是键盘隐藏工具条停留在最底部,因此咱们须要自定义工具条(或者说输入框吧),具体效果如图所示:github
Demo示例工具
这种方式须要在storyboard或xib中找到输入框和父控件(控制器)的约束,代码中的self.bottomConstraint
就是该约束,咱们经过监听键盘的弹出和收回来更改约束的值,再加点动画效果,就是这么简单学习
- (void)viewDidLoad { [super viewDidLoad]; // 监听键盘改变 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillChange:) name:UIKeyboardWillChangeFrameNotification object:nil]; } // 移除监听 - (void)dealloc{ [[NSNotificationCenter defaultCenter] removeObserver:self]; } // 监听键盘的frame即将改变的时候调用 - (void)keyboardWillChange:(NSNotification *)note{ // 得到键盘的frame CGRect frame = [note.userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue]; // 修改底部约束 self.bottomConstraint.constant = self.view.frame.size.height - frame.origin.y; // 执行动画 CGFloat duration = [note.userInfo[UIKeyboardAnimationDurationUserInfoKey] floatValue]; [UIView animateWithDuration:duration animations:^{ // 若是有须要,从新排版 [self.view layoutIfNeeded]; }]; }
此方式大部分代码和上面是同样的,只不过此次咱们不是修改constant了,而是经过transform方式修改输入框 键盘隐藏 和 键盘显示 时 二者y 的 差值(必定要断好句)动画
/** * 设置输入框 */ - (void)setUpToolbar{ BSPostWordToolbar *toolbar = [BSPostWordToolbar viewFromXib]; toolbar.width = self.view.width; toolbar.y = BSScreenH - toolbar.height; // 添加通知监听键盘的弹出与隐藏 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillChangeFrame:) name:UIKeyboardWillChangeFrameNotification object:nil]; [self.view addSubview:toolbar]; self.toolbar = toolbar; } - (void)dealloc{ [[NSNotificationCenter defaultCenter] removeObserver:self]; } - (void)keyboardWillChangeFrame:(NSNotification *)notification{ // 拿到键盘弹出时间 double duration = [notification.userInfo[ UIKeyboardAnimationDurationUserInfoKey ] doubleValue]; // 计算transform CGFloat keyboardY = [notification.userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue].origin.y; CGFloat ty = keyboardY - BSScreenH; /** * 像这种移动后又回到原始位置的建议使用transform,由于transform能够直接清零回到原来的位置 */ [UIView animateWithDuration:duration animations:^{ self.toolbar.transform = CGAffineTransformMakeTranslation(0, ty); }]; }
更多关于iOS学习开发的文章请登录个人我的博客www.zhunjiee.com,欢迎前来参观学习spa