键盘上方添加自定义控件

2017-03-30  本文已影响0人  ios_stand

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];
}
上一篇 下一篇

猜你喜欢

热点阅读