2013-11-09 38 views
3

我覺得自己像一個白癡甚至沒有發佈一些代碼,但在閱讀了幾篇文章,指出iOS7文本套件增加了對文本摺疊的支持後,我實際上找不到任何示例代碼或文本上設置的屬性來摺疊它,而Apple文檔似乎對它靜音。如何摺疊iOS 7中的文字?

http://asciiwwdc.com/2013/sessions/220讓我覺得我設置文本的區域變成自己的文字容器,然後顯示/隱藏它,也許通過重寫setTextContainer:forGlyphRange:

我是望其項背?

感謝

回答

6

有一個WWDC 2013的視頻,討論一些關於它的時候,他們正在做的自定義文本截斷。基本上你實現NSLayoutManagerDelegate方法layoutManager: shouldGenerateGlyphs: properties: characterIndexes: font: forGlyphRange: 我花了太多的掙扎居然想出了這個代碼,但這裏的基礎上的屬性我實現hideNotes

-(NSUInteger)layoutManager:(NSLayoutManager *)layoutManager shouldGenerateGlyphs:(const CGGlyph *)glyphs 
     properties:(const NSGlyphProperty *)props characterIndexes:(const NSUInteger *)charIndexes 
      font:(UIFont *)aFont forGlyphRange:(NSRange)glyphRange { 

    if (self.hideNotes) { 
     NSGlyphProperty *properties = malloc(sizeof(NSGlyphProperty) * glyphRange.length); 
     for (int i = 0; i < glyphRange.length; i++) { 
      NSUInteger glyphIndex = glyphRange.location + i; 
      NSDictionary *charAttributes = [_textStorage attributesAtIndex:glyphIndex effectiveRange:NULL]; 
      if ([[charAttributes objectForKey:CSNoteAttribute] isEqualToNumber:@YES]) { 
       properties[i] = NSGlyphPropertyNull; 
      } else { 
       properties[i] = props[i]; 
      } 
     } 
     [layoutManager setGlyphs:glyphs properties:properties characterIndexes:charIndexes font:aFont forGlyphRange:glyphRange]; 
     return glyphRange.length; 
    } 

    [layoutManager setGlyphs:glyphs properties:props characterIndexes:charIndexes font:aFont forGlyphRange:glyphRange]; 
    return glyphRange.length; 
} 

的NSLayoutManager方法setGlyphs: properties: characterIndexes: font: forGlyphRange:是所謂的默認實現基本上完成了所有的工作。返回值是實際生成的字形的數量,返回0告訴佈局管理器執行其默認實現,因此我只返回它傳入的字形範圍的長度。方法的主要部分遍歷所有字符文本存儲以及它是否具有某個特定屬性時,將關聯的屬性設置爲NSGlyphPropertyNull,它告訴佈局管理器不顯示它,否則它只是將該屬性設置爲傳遞給它的任何內容。

+0

我沒有更好的方法,但沒有attributesAtIndex的危險:如果字形不與字符1:1映射,不會給你預期的值嗎? – griotspeak

+2

爲了避免字形和字符索引之間的不匹配,我認爲glyphIndex應該是「charIndexes [i]」而不是「glyphRange.location + i」。此外,glyphIndex可以更好地重命名爲characterIndex。 – user965972