I'm using iOS7.
I want to change the height of my UITextView dynamically according to the content height. However, I find in iOS7, the contentSize is a mess. For example, when I delete a line, the contentSize will not change, but I expect its height to decrease.
So I write the following
- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text {
// increase a line
if ([text isEqualToString:@"\n"]) {
_FRAME_SET_H(textView, textView.contentSize.height + 24.0f);
// decrease a line
} else if (range.length == 1 && [textView.text hasSuffix:@"\n"]) {
_FRAME_SET_H(textView, textView.contentSize.height - 24.0f);
} else {
_FRAME_SET_H(textView, textView.contentSize.height);
}
return YES;
}
Everything works fine, until I input a very long text:
The contentSize will not change when the text is long enough to cause a automatically line change!
Could anyone help me?
What I want is simple: change the height of the UITextView according to its content. However, I have spent more than two days on it, but still not solved.
The UITextView in iOS7 is so bug.
I tried to follow Uptown Apps's solution. Following is my new code (changed a bit to fit in my other project):
- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text {
return YES;
}
- (void)textViewDidChange:(UITextView *)textView {
CGRect rect = [textView.text
boundingRectWithSize:CGSizeMake(300, CGFLOAT_MAX)
options:NSStringDrawingUsesLineFragmentOrigin
attributes:@{NSFontAttributeName: textView.font}
context:nil];
_FRAME_SET_H(textView, rect.size.height);
_FRAME_SET_H(self, _FRAME_H(textView) + _BLOCK_PADDING * 2);
}
However, trouble remains. In the following image, the white rect is the UITextView, and the black background is its superview.
When I start the app, the UITextView's height is 0, and the screen looks like:
Then I type 'A', the screen turns into:
You see there is two problems: 1) the height is not enough. 2) the caret is strange!
Then I type some more 'a', the screen turns into:
Then I type a 'return' to change a line, the screen turns into:
Yes, it does not change! But I expect it to increase its height to include the new blank line.
Then I type a 'A', the screen turns into:
The height is increased, but the new text is not showing, neither is the caret. I guess it is also due to that the height is not enough.
Then I type another 'a', the screen turns into:
Letters appear, but only a half...
By the way, when I use UILabel, I can get the correct text height using this method!!!! (i.e. calling boundingRectWithSize:)