How to size a UITextView to its content in swift. This works for both iOS 6.1 and iOS 7:
1 2 3 4 5 6 7 8 | - (void)textViewDidChange:(UITextView *)textView { CGFloat fixedWidth = textView.frame.size.width; CGSize newSize = [textView sizeThatFits:CGSizeMake(fixedWidth, MAXFLOAT)]; CGRect newFrame = textView.frame; newFrame.size = CGSizeMake(fmaxf(newSize.width, fixedWidth), newSize.height); textView.frame = newFrame; } |
Or in Swift (Works with Swift 4.1 in iOS 11)
1 2 3 | let fixedWidth = textView.frame.size.width let newSize = textView.sizeThatFits(CGSize(width: fixedWidth, height: CGFloat.greatestFiniteMagnitude)) textView.frame.size = CGSize(width: max(newSize.width, fixedWidth), height: newSize.height) |
If you want support for iOS 6.1 then you should also:
1 | textview.scrollEnabled = NO; |
If you like this question & answer and want to contribute, then write your question & answer and email to freewebmentor[@]gmail.com. Your question and answer will appear on FreeWebMentor.com and help other developers.