How to extend NSTextStorage?

浪子不回头ぞ 提交于 2019-12-05 01:44:13

In addition to the NSAttributedString primitive methods that need implemented, I believe you also need to make a call to edited:range:changeInLength: inside your overrides of replaceCharactersInRange:withString: and setAttributes:range: respectively.

Something like:

- (void) replaceCharactersInRange:(NSRange)range withString:(NSString *)str {
    [storage replaceCharactersInRange:range withString:str];
    [self edited:NSTextStorageEditedCharacters range:range changeInLength:[str length] - range.length];
}

- (void)setAttributes:(NSDictionary *)attrs range:(NSRange)range {
    [storage setAttributes:attrs range:range];
    [self edited:NSTextStorageEditedAttributes range:range changeInLength:0];
}
Greg Titus

The NSTextStorage documentation is a little bit vague in this area. The comment you quote in your question, about only needing to override 2 of the NSMutableAttributedString primitives only means that you don't have to override the other NSMutableAttributedString primitives.

You still have to override the primitives for the NSAttributedString superclass. Which means you need to implement -attributesAtIndex:effectiveRange:, -length and -string. I notice you did include an implementation of -string, so the two remaining ought to do it.

If you add:

- (NSUInteger)length
{
     return [storage length];
}

- (NSDictionary *)attributesAtIndex:(NSUInteger)location effectiveRange:(NSRangePointer)range
{
      return [storage attributesAtIndex:location effectiveRange:range];
}

... then hopefully it will fix this problem.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!