如何在iOS 7中折叠文本?

use*_*952 3 uitextview ios

我觉得自己像个白痴,甚至没有发布一些代码,但在阅读了几篇文章,说明iOS7 Text Kit增加了对文本折叠的支持,我实际上找不到任何示例代码或属性来设置文本折叠它和Apple的文档似乎静音就可以了.

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;
}
Run Code Online (Sandbox Code Playgroud)

NSLayoutManager方法setGlyphs: properties: characterIndexes: font: forGlyphRange:在默认实现中调用,基本上完成所有工作.返回值是实际生成的字形数,返回0告诉布局管理器执行其默认实现,因此我只返回它传入的字形范围的长度.该方法的主要部分遍历所有字符文本存储,如果它具有某个属性,则将关联的属性设置为NSGlyphPropertyNull,告诉布局管理器不显示它,否则它只是将属性设置为传入的属性.

  • 为了避免字形和字符索引之间的不匹配,我认为glyphIndex应该是"charIndexes [i]"而不是"glyphRange.location + i".glyphIndex也可以更好地重命名为characterIndex. (3认同)