ios textView跟随键盘的移动

2022-11-15  本文已影响0人  路漫漫其修远兮Wzt

可以兼容Masonry自动约束。

1.添加通知

//设置两个通知
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(keyHiden:) name: UIKeyboardWillHideNotification object:nil];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(keyWillAppear:) name:UIKeyboardWillChangeFrameNotification object:nil];

2.实现监听

#pragma mark-键盘出现隐藏事件
-(void)keyHiden:(NSNotification *)notification
{
    [UIView animateWithDuration:0.25 animations:^{
        //恢复原样
        _textView.transform = CGAffineTransformIdentity;
    }];
}

-(void)keyWillAppear:(NSNotification *)notification
{
    //获得通知中的info字典
    NSDictionary *userInfo = [notification userInfo];
    CGRect rect= [[userInfo objectForKey:@"UIKeyboardFrameEndUserInfoKey"]CGRectValue];

    [UIView animateWithDuration:0.25 animations:^{
        _textView.transform = CGAffineTransformMakeTranslation(0, -([UIScreen mainScreen].bounds.size.height-rect.origin.y));
    }];
}

3.在合适的地方移除监听

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}
上一篇下一篇

猜你喜欢

热点阅读