问题
How can you make a UITextView expand with the text that is inside of it?
回答1:
you could try this...
UITextView *textView; // your UITextView
NSString *text; // the text that you want to place in the UITextView
UIFont *textViewFont; // the font that you are using for your UITextView
CGSize size = {255,2000.0f}; //The default width, and max height you want to use
CGSize newSize = [text sizeWithFont:textViewFont
constrainedToSize:size lineBreakMode:UILineBreakModeWordWrap];
textView.frame = CGRectMake(0,0,newSize.width, newSize.height);
回答2:
You can try this..
CGRect frame = textView.frame;
frame.size.height = [textView contentSize].height;
textView.frame = frame;
回答3:
Are you using UITextView inside UITableView?
Let's suppose you are using UITextView inside UITableView. In order to make UITextView height dynamic(As per the content inside it) we need to take care of following things:-
Make sure UITextView constraints are properly given. e.g: I had used XIB for tableview cell and inside cell I had a UITextView. So, I will give constraint to UITextView 0 to all four sides e.g: Top, bottom, leading, trailing. (Depends on your requirements).
Make sure UITextView attribute, autoscroll is disabled. It should be off.
Make sure TableView cell height is UITableView.automaticDimension
Now inside your 'textViewDidChange' delegate method, Just add this below mentioned code:
UIView.setAnimationsEnabled(false) tableView?.beginUpdates() tableView?.endUpdates() UIView.setAnimationsEnabled(true)
Now your textView will auto expand, while you are typing init.
来源:https://stackoverflow.com/questions/2097850/how-to-make-a-uitextview-expand-with-the-text-like-the-notes-app