原理:監(jiān)聽鍵盤的兩個(gè)方法willAppearance 和willDismiss獲取鍵盤的范圍,然后設(shè)置textfield與底部約束的值。添加鍵盤監(jiān)聽
//添加鍵盤監(jiān)聽
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillAppearance:) name:UIKeyboardWillShowNotification object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillDismiss:) name:UIKeyboardWillHideNotification object:nil];
然后在監(jiān)聽辦法中獲取鍵盤的高度:這里的_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;
最后記得將監(jiān)聽移除:
-(void)viewWillDisappear:(BOOL)animated {
[[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
[[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];
}
如果能輸入的文字比較長,在輸入的時(shí)候,文字應(yīng)該能往上移胆敞,可以設(shè)置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 內(nèi)容
* @param labelWidth label的寬度
* @param font 文本的字體
*
* @return label的合適尺寸
- (CGSize)getLabelFitSize:(NSString *)content labelWidth:(CGFloat)labelWidth font:(UIFont *)font {
CGSize size = CGSizeMake(labelWidth, MAXFLOAT); // 設(shè)置一個(gè)行高上限
CGSize returnSize;
NSDictionary *attribute = @{ NSFontAttributeName: font };
returnSize = [content boundingRectWithSize:size
options:NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading
attributes:attribute
context:nil].size;
return returnSize;
}