ios - UITextView:在截断文本中查找省略号的位置
<p><p>我有一个带有一些属性文本的 <code>UITextView</code>,其中设置了 <code>textContainer.maximumNumberOfLine</code>(在本例中为 3)。</p>
<p>我想在属性字符串的字符范围内找到省略号字符的索引。</p>
<p>例如:</p>
<p>原始字符串:</p>
<p><code>“Lorem ipsum dolor sit amet, consectetur adipiscing elit”</code></p>
<p>截断后显示的字符串:</p>
<p><code>Lorem ipsum
dolor 坐在一起,
结构...</code></p>
<p>如何确定<code>...</code>的索引?</p></p>
<br><hr><h1><strong>Best Answer-推荐答案</ strong></h1><br>
<p><p>这是 NSAttributedString 的扩展函数,它可以完成这项工作。适用于单行和多行文本。</p>
<p>我花了大约 8 个小时才弄清楚,所以我想我会把它作为问答发布。</p>
<p>( swift2.2)</p>
<pre><code>/**
Returns the index of the ellipsis, if this attributed string is truncated, or NSNotFound otherwise.
*/
func truncationIndex(maximumNumberOfLines: Int, width: CGFloat) -> Int {
//Create a dummy text container, used for measuring & laying out the text..
let textContainer = NSTextContainer(size: CGSize(width: width, height: CGFloat.max))
textContainer.maximumNumberOfLines = maximumNumberOfLines
textContainer.lineBreakMode = NSLineBreakMode.ByTruncatingTail
let layoutManager = NSLayoutManager()
layoutManager.addTextContainer(textContainer)
let textStorage = NSTextStorage(attributedString: self)
textStorage.addLayoutManager(layoutManager)
//Determine the range of all Glpyhs within the string
var glyphRange = NSRange()
layoutManager.glyphRangeForCharacterRange(NSMakeRange(0, self.length), actualCharacterRange: &glyphRange)
var truncationIndex = NSNotFound
//Iterate over each 'line fragment' (each line as it's presented, according to your `textContainer.lineBreakMode`)
var i = 0
layoutManager.enumerateLineFragmentsForGlyphRange(glyphRange) { (rect, usedRect, textContainer, glyphRange, stop) in
if (i == maximumNumberOfLines - 1) {
//We're now looking at the last visible line (the one at which text will be truncated)
let lineFragmentTruncatedGlyphIndex = glyphRange.location
if lineFragmentTruncatedGlyphIndex != NSNotFound {
truncationIndex = layoutManager.truncatedGlyphRangeInLineFragmentForGlyphAtIndex(lineFragmentTruncatedGlyphIndex).location
}
stop.memory = true
}
i += 1
}
return truncationIndex
}
</code></pre>
<p>请注意,除了一些简单的情况外,这还没有经过测试。可能存在需要一些调整的边缘情况..</p></p>
<p style="font-size: 20px;">关于ios - UITextView:在截断文本中查找省略号的位置,我们在Stack Overflow上找到一个类似的问题:
<a href="https://stackoverflow.com/questions/41628215/" rel="noreferrer noopener nofollow" style="color: red;">
https://stackoverflow.com/questions/41628215/
</a>
</p>
页:
[1]