如何在iOS 7中折叠文本?

3

我感觉自己像个傻瓜,因为我甚至没有发布任何代码,但在阅读了几篇文章后,发现iOS7 Text Kit支持文本折叠,但实际上我找不到任何示例代码或要设置的属性以折叠文本,苹果的文档似乎对此没有提及。

http://asciiwwdc.com/2013/sessions/220 让我想到将文本区域设置为自己的文本容器,然后通过覆盖setTextContainer:forGlyphRange:来显示/隐藏它。

我接近了吗?

谢谢

1个回答

7

在2013年的WWDC视频中,涉及到一些自定义文本截断的内容。基本上通过实现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,这告诉布局管理器不要显示它,否则它只是将属性设置为传递给它的任何内容。


我没有更好的方法,但如果字形与字符不是一对一映射的话,attributesAtIndex: 不会给你期望的值,这不是有风险吗? - griotspeak
3
为避免字形和字符索引之间的不匹配,我认为glyphIndex应该改为“charIndexes [i]”,而不是“glyphRange.location + i”。此外,glyphIndex最好更名为characterIndex。 - user965972

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接