Dynamic size of UITextView based on content in Swift

I don’t think anyone can direct me to the correct way to dynamically size a UITextView when using Auto-Layout? Using Swift, that is.

I tried to programmatically set the lower limits, trying to get the UITextView to cuddle the content. But I'm not sure how to get the height of the contents of a UITextView?

I try to load data into UITextView fields, then dynamically tune them to make them look neat.

@IBOutlet weak var serviceDescriptionTextViewBottomGuide: NSLayoutConstraint! override func viewDidLoad() { self.activityName.text = serviceCodes[selectionValue] self.serviceDescriptionTextView.text = serviceDescription[selectionValue] self.whenToUseDescriptionTextView.text = whenToUseCode[selectionValue] self.serviceDescriptionTextViewBottomGuide?.constant += x } 

enter image description here

+6
source share
3 answers

Disable scrolling and do not set any other restrictions that may determine the height of the UITextView.

+33
source

You can create an IBOutlet for any constraint that you want to change programmatically. Then change the constraint using the NSLayoutConstraint constant property in the code through its output link. It works very well. You can distinguish between width, height and position in this way. You cannot change the NSLayoutConstraint multiplier property, though (it is read-only). But that doesn’t matter, because what you could accomplish by defining the constraint multiplier property in Interface Builder (to get a proportional value), you can also accomplish by doing the math in your code and changing the constant property.

Alternative approach: you can disable the translation of the resize mask (for example, the UIView translatesAutoresizingMaskIntoConstraints property set to nil) and create software restrictions from scratch for which the recommended approach (easier to use) is called the visual format. But creating constraints entirely in software is more work than using the Autolayout Interface Builder to create an rough draft of your views, and then by selectively selecting software constraints after the fact, at least in typical simple cases.

+1
source

This is correct, but I also had to write:

 override func viewDidLoad() { super.viewDidLoad() tableView.estimatedRowHeight = 44.0 // Replace with your actual estimation // Automatic dimensions to tell the table view to use dynamic height tableView.rowHeight = UITableViewAutomaticDimension } 

More details:

https://pontifex.azurewebsites.net/self-sizing-uitableviewcell-with-uitextview-in-ios-8/

+1
source

Source: https://habr.com/ru/post/984591/


All Articles