Skip to content

Instantly share code, notes, and snippets.

@soffes
Last active July 1, 2023 10:14
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save soffes/4d484f0683313efb8d3fdd0ea8baee21 to your computer and use it in GitHub Desktop.
Save soffes/4d484f0683313efb8d3fdd0ea8baee21 to your computer and use it in GitHub Desktop.
BaseTextStorage (Objective-C)
@import Darwin.TargetConditionals;
#if TARGET_OS_IPHONE
@import UIKit;
#else
@import AppKit;
#endif
/// Concrete text storage intended to be subclassed.
@interface BaseTextStorage : NSTextStorage
@end
#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