键盘上方添加自定义控件

toobar在屏幕上,控制器监听键盘的弹出退下:

[[NSNotificationCenter defaultCenter] addObserver:self
    selector:@selector(keyboardWillChangeFrame:) name:
     UIKeyboardWillChangeFrameNotification object:nil];
/**
 * 监听键盘的弹出和隐藏
 */
- (void)keyboardWillChangeFrame:(NSNotification *)note
{
    // 键盘最终的frame
    CGRect keyboardF = [note.userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue];
    
    // 动画时间
    CGFloat duration = [note.userInfo[UIKeyboardAnimationDurationUserInfoKey] doubleValue];
    
    [UIView animateWithDuration:duration animations:^{
        // toobar为键盘上方的自定义工具条
        self.toolbar.transform = CGAffineTransformMakeTranslation(0,  keyboardF.origin.y - [UIScreen mainScreen].bounds.size.height);
    }];
}

toobar不显示屏幕上,按钮点击才出现toobar(类似微信朋友圈点评论弹出键盘):

- (void)viewDidLoad {
    [super viewDidLoad];
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWillChangeFrame:) name:
     UIKeyboardWillChangeFrameNotification object:nil];
    //创建toobar在屏幕下方
    _toolbar = [[UITextField alloc]initWithFrame:CGRectMake(0, [UIScreen mainScreen].bounds.size.height  , [UIScreen mainScreen].bounds.size.width, 30)];
    _toolbar.borderStyle = UITextBorderStyleRoundedRect;
    [self.view addSubview:_toolbar];
    
}

- (void)keyboardWillChangeFrame:(NSNotification *)note
{
    // 键盘最终的frame
    CGRect keyboardF = [note.userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue];
    
    // 动画时间
    CGFloat duration = [note.userInfo[UIKeyboardAnimationDurationUserInfoKey] doubleValue];
//    NSLog(@"%f",[UIScreen mainScreen].bounds.size.height);
    
    
    [UIView animateWithDuration:duration animations:^{
        // toobar为键盘上方的自定义工具条
        CGFloat x = 0;
        if (keyboardF.origin.y - [UIScreen mainScreen].bounds.size.height == 0) {
            x = keyboardF.origin.y - [UIScreen mainScreen].bounds.size.height;
        }else{
            x = keyboardF.origin.y - [UIScreen mainScreen].bounds.size.height - _toolbar.frame.size.height;
        }
        self.toolbar.transform = CGAffineTransformMakeTranslation(0,  x );
    }];
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    [_toolbar resignFirstResponder];
}


- (IBAction)onClick:(id)sender {
    [_toolbar becomeFirstResponder];
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 发现 关注 消息 iOS 第三方库、插件、知名博客总结 作者大灰狼的小绵羊哥哥关注 2017.06.26 09:4...
    肇东周阅读 12,198评论 4 61
  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 173,020评论 25 708
  • 在Finder的偏好设置->高级->执行搜索时 选择搜索当前文件夹即可
    就叫初九吧阅读 2,304评论 0 1
  • 墨色渲染的天空 挽回不了,雨滴的离去 昂扬挺拔的银杏 挽回不了,黄叶的飘离 孑然一身的我 挽回不了,已到的离别 但...
    尚谙阅读 121评论 2 1
  • 就在昨天,突然想通了,我决定放手。于是,约三两个好友,出来一聚。 回家的路上,偶遇一个陌生人,大概...
    大大小小邹阅读 238评论 0 0