我正在为 iOS/osx 编写语法降价。
它是 NSTextStorage 的子类。它在 iOS 中运行良好,但在 OSX 中(在将代码转换为 UIColor 到 NSColor 和 UIFont 到 NSFont 之后)它运行得非常好。如果我在当前行的末尾写它会很好,但是如果我将插入符号位置更改为文本中间,就在键入 1 个字母后,它会将插入符号位置更改为行尾。这只是在 OSX 中发生,因为在 IOS 中它工作得很好。
我知道问题出在哪里,- (void)setAttributes:(NSDictionary *)attrs range:(NSRange)range
但不知道如何解决……有什么帮助吗?
- (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];
}];
}];
}