How to get CATextLayer’s wrapping count in order t

2019-06-03 11:04发布

问题:

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.

回答1:

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.



回答2:

Well, I ended up forgoing CATextLayer's wrapping behavior and doing my own line breaks -- which I would have had to do in this case anyway because I'm using different fonts for different lines, causing variations in their size.

But I don't understand why CATextLayer doesn't allow access to what its wrapping functions are doing -- either adding the line breaks to the string property itself, which we could then access, or simply providing a "lineCount" read-only accessor.