我正在为iOS/osx编写一个语法标记。
它是NSTextStorage的一个子类。它在iOS中工作得很好,但在OSX中(在转换代码后,将UIColor转换为NSColor,将UIFont转换为NSFont),它确实工作得很好。这只是在OSX中发生的,因为在IOS中它工作得很好。
有什么帮助吗?
- (NSString *)string {
return [_backingStore string];
}
- (NSDictionary *)attributesAtIndex:(NSUInteger)location effectiveRange:(NSRangePointer)range {
return [_backingStore attributesAtIndex:location effectiveRange:range];
}
- (void)replaceCharactersInRange:(NSRange)range withString:(NSString*)str {
[self beginEditing];
[_backingStore replaceCharactersInRange:range withString:str];
[self edited:NSTextStorageEditedCharacters | NSTextStorageEditedAttributes range:range changeInLength:str.length - range.length];
[self endEditing];
}
- (void)setAttributes:(NSDictionary *)attrs range:(NSRange)range {
[self beginEditing];
[_backingStore setAttributes:attrs range:range];
[self edited:NSTextStorageEditedAttributes range:range changeInLength:0];
[self endEditing];
}
- (void)processEditing {
[self performReplacementsForRange:[self editedRange]];
[super processEditing];
}
- (void)performReplacementsForRange:(NSRange)changedRange {
NSString* backingString = [_backingStore string];
NSRange extendedRange = extendedRange = NSUnionRange(changedRange, [backingString lineRangeForRange:NSMakeRange(NSMaxRange(changedRange), 0)]);
[self applyStylesToRange:extendedRange];
}
- (void)applyStylesToRange:(NSRange)searchRange {
NSDictionary* attributeDictionary = self.attributeDictionary;
NSString* backingString = [_backingStore string];
NSDictionary* bodyAttributes = self.bodyAttributes;
[self setAttributes:bodyAttributes range:searchRange];
[attributeDictionary enumerateKeysAndObjectsUsingBlock:^(NSRegularExpression* regex, NSDictionary* attributes, BOOL* stop) {
[regex enumerateMatchesInString:backingString options:0 range:searchRange
usingBlock:^(NSTextCheckingResult *match, NSMatchingFlags flags, BOOL *stop) {
NSRange matchRange = [match rangeAtIndex:1];
[self addAttributes:attributes range:matchRange];
}];
}];
}发布于 2016-02-22 00:05:02
我不熟悉NSTextStorage,但是我通过重写fixAttributesInRange:而不是processEditing来解决这个问题。
而不是
- (void)processEditing {
[self performReplacementsForRange:[self editedRange]];
[super processEditing];
}做
- (void)fixAttributesInRange:(NSRange)range {
[self performReplacementsForRange:range];
[super fixAttributesInRange:(NSRange)range];
}顺便说一句:applyStylesToRange不应该嵌套在beginEditing和endEditing之间吗
https://stackoverflow.com/questions/35522394
复制相似问题