Reputation: 13178
I've seen a lot of questions related to this on SO, however, none of them pertain to my question.
I'm to create an app that has a messaging functionality. Similar to how Apple has Mail and LinkedIn has it's Mail feature in their app, I would like to have a UITableView
with 3 rows. The third row has the UITextView
which has to grow as the user types. My code is below:
- (void)textViewDidChange:(UITextView *)textView {
if (bodyText.contentSize.height > currentContentHeight) {
currentContentHeight = bodyText.contentSize.height;
[tblView beginUpdates];
[tblView endUpdates];
[bodyText setFrame:CGRectMake(0, 0, 310.0, currentContentHeight)];
bodyText.selectedRange = NSMakeRange(textView.text.length - 1, 0);
} else {
currentContentHeight = minimumContentHeight;
[tblView beginUpdates];
[tblView endUpdates];
}
}
When I press return on the iPhone it goes down and works flawlessly. Problem is that if I goto the center or any other middle part of the UITextView
, it seems to create funny behaviour because it's getting the contentSize
incorrectly. For example:
contentHeight
based on that 5th line, if that makes sense?Is there a way to calculate it based on all of the text currently? Please let me know if there is anything I have missed above. I read the following extensively:
http://dennisreimann.de/blog/uitextview-height-in-uitableviewcell/
https://stackoverflow.com/questions/985394/growing-uitextview-and-uitableviewcell
UITextView inside a UITableViewCell
How do I size a UITextView to its content?
Upvotes: 1
Views: 1024
Reputation: 13178
I edited the code above with the following and it's working for me:
- (void)textViewDidChange:(UITextView *)textView {
// Get the number of lines in the current view
NSUInteger lines = textView.text.length;
if ((lines * 25) > currentContentHeight && (lines * 25) >= minimumContentHeight && bodyText.contentSize.height > minimumContentHeight) {
currentContentHeight = bodyText.contentSize.height;
} else if (lines < 5){
currentContentHeight = minimumContentHeight;
}
[tblView beginUpdates];
[tblView endUpdates];
[bodyText setFrame:CGRectMake(5, 5, 310, currentContentHeight)];
bodyText.selectedRange = [bodyText selectedRange];
}
I set the currentContentHeight
equal to the minimumContentHeight
in the beginning based on the size of the phone.
Upvotes: 2