Uitextview - Adjust Size Based on the Content in Swiftui

How do I size a UITextView to its content?

This works for both iOS 6.1 and iOS 7:

- (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)

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:

textview.scrollEnabled = NO;

how to make UITextView height dynamic according to text length?

this Works for me, all other solutions didn't.

func adjustUITextViewHeight(arg : UITextView) {
arg.translatesAutoresizingMaskIntoConstraints = true
arg.sizeToFit()
arg.scrollEnabled = false
}

In Swift 4 the syntax of arg.scrollEnabled = false has changed to arg.isScrollEnabled = false.

Dynamically adjust the height of the UITextView depending on its content?

Setup your constraints so that the edges are pinned but allow the text view to grow vertically. Then set a height constraint (the value doesn't matter here). Create an @IBOutlet for the UITextView and the height constraint. Then we can dynamically change the height in code:

class ViewControler: UIViewController, UITextViewDelegate {

@IBOutlet weak var textView: UITextView!
@IBOutlet weak var textViewHeight: NSLayoutConstraint!

override func viewDidLoad() {
super.viewDidLoad()
self.textView.delegate = self
}

func textViewDidChange(textView: UITextView) {
let sizeToFitIn = CGSizeMake(self.textView.bounds.size.width, CGFloat(MAXFLOAT))
let newSize = self.textView.sizeThatFits(sizeToFitIn)
self.textViewHeight.constant = newSize.height
}

}


Related Topics



Leave a reply



Submit