Define UITextView width in heightForRowAtIndexPath with auto layout

A rather difficult problem, looking for an elegant solution:

Subclass

A UITableViewCell has a UILabel on the left and a UITextView on the right. Both labels and text presentation have dynamic content . I use a textual representation and not another shortcut because I need address link recognition.

A label has a higher compression resistance than a text representation, so its right edge will expand to the right as necessary (up to a certain limit). In turn, the width of the text will be compressed. The text view is set to wrap words on expand down .

Since the text view itself is a UIScrollView , the normal automatic cell dimension mechanism of a table view with a dynamic view size does not work (i.e. using the UITableViewAutomaticDimension ). So I tried to implement heightForRowAtIndexPath . To determine the required height, I just needed:

  • text in the label plus its attributes
  • text in text view plus its attributes
  • the width of the table view (since it is "simple", not "grouped")

With this information, I figured I could use sizeThatFits for helper objects to determine the required height.

However, I do not want to hard-code the horizontal margins between the label and the text representation in my dimensional calculation, so theoretically I also need the NSLayoutConstraint outputs for

  • Left label label to his supervisor
  • Maximum Label Width
  • The horizontal distance between the label and the text box
  • Correct margin of a text field in its supervisor

It seems insane! As I wrote about this, I asked myself if there was an easier way to do the same. (That's why I haven't written code to post here yet.) After all, the only difficult problem here is how to get the available width for the text view , but the way to get there seems unreasonable.

Any ideas for a concise, elegant solution?

Side notes: this should be calculated before the displayed cell is displayed. Also, setting the scrollingEnabled text view to false results in strange results when using sizeThatFits .

+5
source share

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


All Articles