美文网首页
ios textView跟随键盘的移动

ios textView跟随键盘的移动

作者: 路漫漫其修远兮Wzt | 来源:发表于2022-11-15 10:17 被阅读0次

    可以兼容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];
    }
    

    相关文章

      网友评论

          本文标题:ios textView跟随键盘的移动

          本文链接:https://www.haomeiwen.com/subject/behdxdtx.html