objective-ciosuiscrollviewword-wrapcatextlayer

How to get CATextLayer’s wrapping count in order to calculate height


I am adding text incrementally to a wrapping CATextLayer in a UIScrollView. Each time I add text, I need to add height to the textLayer and to the scrollView’s contentSize, and adjust the scrollView’s contentOffset.

(The user should be able to use the scrollView to review previous text, but when new text is added, I want to scroll down to it programmatically.)

UIKit’s sizeWithFont: will treat the entire string as though it is on one line, so in order to calculate the height, I need to multiple the size.height returned by the number of lines, as produced by the textLayer’s wrapping.

Trouble is, if I access the string through the textLayer, it won’t contain any extra ‘\n’ or ‘\r’ characters to account for the wrapping.

Surely there is some way I can get the wrapping info? Perhaps dervied from superclass CALayer somehow? Otherwise I’m stuck calculating my own line breaks.


Solution

  • I assume that CATextLayer internally uses Core Text for layout, so you could do the same and use CTFramesetterSuggestFrameSizeWithConstraints to calculate an appropriate height for an attributed string with a given width.