2017-01-13 84 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