如何获取 CATextLayer 的环绕计数以计算高度 [英] How to get CATextLayer’s wrapping count in order to calculate height
问题描述
我正在将文本增量添加到 UIScrollView
中的包装 CATextLayer
.每次添加文本时,都需要给textLayer和scrollView的contentSize
添加高度,并调整scrollView的contentOffset
.
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
.
(用户应该能够使用 scrollView 查看以前的文本,但是当添加新文本时,我想以编程方式向下滚动到它.)
(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 的 sizeWithFont:
会将整个字符串视为在一行上,因此为了计算高度,我需要乘以行数返回的 size.height,如由 textLayer 的包装产生.
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.
问题是,如果我通过 textLayer 访问字符串,它不会包含任何额外的\n"或\r"字符来解释换行.
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.
当然有某种方法可以获得包装信息吗?也许以某种方式源自超类 CALayer
?否则我会被困在计算自己的换行符中.
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.
推荐答案
我假设 CATextLayer
在内部使用 Core Text 进行布局,所以你可以这样做并使用 CTFramesetterSuggestFrameSizeWithConstraints
为具有给定宽度的属性字符串计算适当的高度.
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.
这篇关于如何获取 CATextLayer 的环绕计数以计算高度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!