TextKit中的字形无效

时间:2013-11-08 18:51:24

标签: ios layout ios7 glyph textkit

我正在尝试实现文本折叠效果,以根据文本存储中的属性隐藏UITextView中的一些文本,然后在layoutManager: shouldGenerateGlyphs: properties: characterIndexes: font:(UIFont *)aFont forGlyphRange:(NSRange)glyphRange方法中将这些字形属性设置为NSGlyphPropertyNull。到目前为止,这部分工作得很好,并且做了预期的事情。问题是当我尝试强制文本视图的布局管理器重新布局文本时。我已经尝试调用所有无效方法,但只有一个有效,invalidateGlyphsForCharacterRange: changeInLength: actualCharacterRange:。我传入了整个字符范围,0表示changeInLength,因为我实际上没有更改任何内容,而NULL表示actualCharacterRange。每隔一段时间,这个工作就好了。但大部分时间我都会收到此错误Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'The index -4097 is invalid'。这有什么问题?以下是我的一些代码:

-(IBAction)showHideNotes:(id)sender {
    self.hideNotes = !self.hideNotes;
    [self.textView.layoutManager invalidateGlyphsForCharacterRange:NSMakeRange(0, _textStorage.string.length) changeInLength:0 actualCharacterRange:NULL];
    [self.textView setNeedsLayout];
}

基本上我的目标是当用户点击按钮时,文本将因此而折叠或展开。在UILayoutManagerDelegate方法layoutManager: shouldGenerateGlyphs: properties: characterIndexes: font: forGlyphRange:中,我只在self.hiddenYES

时才将我想隐藏的字形设置为NSGlyphPropertyNull

1 个答案:

答案 0 :(得分:0)

查看invalidateGlyphsForCharacterRange:changeInLength:actualCharacterRange:的文档:

  

此方法仅使字形信息无效,并且不执行字形生成或布局。因为使字形无效也使布局无效,所以在调用此方法之后还应该调用invalidateLayoutForCharacterRange:actualCharacterRange:,将charRange作为第一个参数传递。

同时确保您遵守此方法的其他记录限制:

  

此方法由布局机制使用,并且应仅在排版期间调用,几乎在所有情况下仅由布局管理器调用。例如,自定义布局管理器可能会调用它。

当你说你正在设置字形时,你的意思是你在委托方法中调用setGlyphs:properties:characterIndexes:font:forGlyphRange:吗?这样做应该足以使字形无效。 (“为先前计算过的布局信息的字符范围调用此方法会使布局和显示无效。”)