UITextView:在截断文本中查找省略号的位置 [英] UITextView: Find location of ellipsis in truncated text

查看:71
本文介绍了UITextView:在截断文本中查找省略号的位置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有一些属性文本的 UITextView,其中设置了 textContainer.maximumNumberOfLine(在本例中为 3).

I have a UITextView with some attributed text, where the textContainer.maximumNumberOfLine is set (3 in this case).

我想在属性字符串的字符范围内找到省略号字符的索引.

I'd like to find the index of the ellipsis character within the character range of the attributed string.

例如:

原始字符串:

Lorem ipsum dolor sat amet, consectetur adipiscing elit"

截断后显示的字符串:

Lorem ipsum多洛尔坐下来,连续...

如何确定...的索引?

推荐答案

这是一个 NSAttributedString 的扩展函数,它完成了这项工作.单人和作品多行文本.

Here's an extension function to NSAttributedString which does the job. Works for single & multiline text.

我花了大约 8 个小时才弄明白,所以我想把它作为问答发布.

This took me all of about 8 hours to figure out, so I thought I'd post it as a Q&A.

(斯威夫特 2.2)

/**
    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
}

请注意,除了一些简单的情况外,这还没有经过测试.可能存在需要一些调整的边缘情况..

Note that this has not been tested beyond some simple cases. There may be edge cases requiring some adjustments..

这篇关于UITextView:在截断文本中查找省略号的位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆