输入框跟随键盘移动效果的实现

inputAccessoryView : 系统自带的键盘上面的工具条视图(并没有什么卵用)

由于系统自带的工具条随着键盘的隐藏也一起隐藏了,而现在很多应用的需求的是键盘隐藏工具条停留在最底部,所以我们需要自定义工具条(或者说输入框吧),具体效果如图所示:

Demo示例

方式一:修改约束 constant 方式

  • 这种方式需要在storyboard或xib中找到输入框和父控件(控制器)的约束,代码中的self.bottomConstraint就是该约束,我们通过监听键盘的弹出和收回来更改约束的值,再加点动画效果,就是这么简单

     1 - (void)viewDidLoad {
     2     [super viewDidLoad];
     3 
     4     // 监听键盘改变
     5     [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillChange:) name:UIKeyboardWillChangeFrameNotification object:nil];
     6 }
     7 
     8 // 移除监听
     9 - (void)dealloc{
    10     [[NSNotificationCenter defaultCenter] removeObserver:self];
    11 }
    12 
    13 
    14 // 监听键盘的frame即将改变的时候调用
    15 - (void)keyboardWillChange:(NSNotification *)note{
    16     // 获得键盘的frame
    17     CGRect frame = [note.userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue];
    18 
    19     // 修改底部约束
    20     self.bottomConstraint.constant = self.view.frame.size.height - frame.origin.y;
    21 
    22     // 执行动画
    23     CGFloat duration = [note.userInfo[UIKeyboardAnimationDurationUserInfoKey] floatValue];
    24     [UIView animateWithDuration:duration animations:^{
    25         // 如果有需要,重新排版
    26         [self.view layoutIfNeeded];
    27     }];
    28 }

方式二:transform 方式

  • 此方式大部分代码和上面是一样的,只不过这次我们不是修改constant了,而是通过transform方式修改输入框 键盘隐藏 和 键盘显示 时 两者y 的 差值(一定要断好句)

 1 /**
 2  *  设置输入框
 3  */
 4 - (void)setUpToolbar{
 5     BSPostWordToolbar *toolbar = [BSPostWordToolbar viewFromXib];
 6     toolbar.width = self.view.width;
 7     toolbar.y = BSScreenH - toolbar.height;
 8     
 9     // 添加通知监听键盘的弹出与隐藏
10     [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillChangeFrame:) name:UIKeyboardWillChangeFrameNotification object:nil];
11     
12     
13     [self.view addSubview:toolbar];
14     self.toolbar = toolbar;
15 }
16 
17 - (void)dealloc{
18     [[NSNotificationCenter defaultCenter] removeObserver:self];
19 }
20 
21 - (void)keyboardWillChangeFrame:(NSNotification *)notification{
22     // 拿到键盘弹出时间
23     double duration = [notification.userInfo[
24 UIKeyboardAnimationDurationUserInfoKey
25 ] doubleValue];
26 
27     // 计算transform
28     CGFloat keyboardY = [notification.userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue].origin.y;
29     CGFloat ty = keyboardY - BSScreenH;
30     
31     /**
32      *  像这种移动后又回到原始位置的建议使用transform,因为transform可以直接清零回到原来的位置
33      */
34     [UIView animateWithDuration:duration animations:^{
35         self.toolbar.transform = CGAffineTransformMakeTranslation(0, ty);
36     }];
37 }

 

do or nothing
原文地址:https://www.cnblogs.com/LYW1993-1024/p/8350176.html