2017-01-13 58 views
1

我有一个UITextView带有一些归因文本,其中textContainer.maximumNumberOfLine已设置(本例中为3)。UITextView:在截短文本中查找省略号的位置

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

E.g:

原始字符串:

"Lorem ipsum dolor sit amet, consectetur adipiscing elit"

String作为显示,截断后:

Lorem ipsum dolor sit amet, consectetur...

如何确定...的指数?

回答

2

这是NSAttributedString的扩展函数,它执行这项工作。适用于单行文本&。

这花了我所有的约8小时搞清楚,所以我想我会发布它作为问答& 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 
} 

注意,这还没有已经过一些简单的例子测试。可能有边缘情况下需要一些调整..

+0

很不错的方法 – greenisus