Last active
July 1, 2023 10:14
-
-
Save soffes/4d484f0683313efb8d3fdd0ea8baee21 to your computer and use it in GitHub Desktop.
BaseTextStorage (Objective-C)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@import Darwin.TargetConditionals; | |
#if TARGET_OS_IPHONE | |
@import UIKit; | |
#else | |
@import AppKit; | |
#endif | |
/// Concrete text storage intended to be subclassed. | |
@interface BaseTextStorage : NSTextStorage | |
@end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#import "BaseTextStorage.h" | |
@interface BaseTextStorage () | |
@property (nonatomic) NSMutableAttributedString *storage; | |
@end | |
@implementation BaseTextStorage | |
@synthesize storage = _storage; | |
// MARK: - Initializers | |
- (instancetype)init { | |
if ((self = [super init])) { | |
self.storage = [[NSMutableAttributedString alloc] init]; | |
} | |
return self; | |
} | |
// MARK: - NSTextStorage | |
- (NSString *)string { | |
return self.storage.string; | |
} | |
- (NSDictionary<NSString *,id> *)attributesAtIndex:(NSUInteger)location effectiveRange:(NSRangePointer)effectiveRange { | |
return [self.storage attributesAtIndex:location effectiveRange:effectiveRange]; | |
} | |
- (void)replaceCharactersInRange:(NSRange)range withString:(NSString *)aString { | |
[self.storage replaceCharactersInRange:range withString:aString]; | |
NSInteger change = aString.length - range.length; | |
[self edited:NSTextStorageEditedCharacters range:range changeInLength:change]; | |
} | |
- (void)setAttributes:(NSDictionary<NSString *,id> *)attributes range:(NSRange)range { | |
if (NSMaxRange(range) > self.length) { | |
NSLog(@"WARNING: Tried to set attributes at out of bounds range %@. Length: %lu", NSStringFromRange(range), | |
(unsigned long)self.length); | |
return; | |
} | |
[self beginEditing]; | |
[self.storage setAttributes:attributes range:range]; | |
[self edited:NSTextStorageEditedAttributes range:range changeInLength:0]; | |
[self endEditing]; | |
} | |
@end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment