美文网首页Objective C开发
iOS textview 随键盘移动

iOS textview 随键盘移动

作者: 34码的小孩子 | 来源:发表于2016-08-23 14:28 被阅读449次

原理:监听键盘的两个方法willAppearance 和willDismiss获取键盘的范围,然后设置textfield与底部约束的值。添加键盘监听

//添加键盘监听
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillAppearance:) name:UIKeyboardWillShowNotification object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillDismiss:) name:UIKeyboardWillHideNotification object:nil];

然后在监听办法中获取键盘的高度:这里的_textViewBottomConstraint是指textview和父容器底部的约束。

    CGRect keyboardFrame =    [notification.userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue];
    CGFloat height = self.view.frame.size.height - keyboardFrame.origin.y;

    if (height == 0) {
        height = 15;
    }
    else {
        height = height - 40;
    }
    _textViewBottomConstraint.constant = height;

最后记得将监听移除:

-(void)viewWillDisappear:(BOOL)animated {
[[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
[[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];
}

如果能输入的文字比较长,在输入的时候,文字应该能往上移,可以设置textview的高度约束,并在UITextViewDelegate的方法textViewDidChange中获取文字的高度,并修改textView的高度约束:

-(void)textViewDidChange:(UITextView *)textView {
CGFloat height = [self getLabelFitSize:toBeString labelWidth:UI_SCREEN_FWIDTH - 30 font:F3].height;

if (height > _textViewHeightConstraint.constant) {
    _textViewHeightConstraint.constant = height;
}
}

 *  获得label的合适尺寸
 *
 *  @param content    内容
 *  @param labelWidth label的宽度
 *  @param font       文本的字体
 *
 *  @return label的合适尺寸
- (CGSize)getLabelFitSize:(NSString *)content labelWidth:(CGFloat)labelWidth font:(UIFont *)font {
CGSize size = CGSizeMake(labelWidth, MAXFLOAT); // 设置一个行高上限
CGSize returnSize;

NSDictionary *attribute = @{ NSFontAttributeName: font };
returnSize = [content boundingRectWithSize:size
                                   options:NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading
                                attributes:attribute
                                   context:nil].size;

return returnSize;
}

相关文章

网友评论

    本文标题:iOS textview 随键盘移动

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