Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save SKaplanOfficial/e73a7a37ec49584a261c446e152dec35 to your computer and use it in GitHub Desktop.
Save SKaplanOfficial/e73a7a37ec49584a261c446e152dec35 to your computer and use it in GitHub Desktop.
Base subclass of NSTextStorage in Swift
import Cocoa
@objc
class SomeTextStorage: NSTextStorage {
private var storage: NSMutableAttributedString
override init() {
storage = NSMutableAttributedString(string: "", attributes: nil)
super.init()
}
required init?(coder aDecoder: NSCoder) {
fatalError("\(__FUNCTION__) is not supported")
}
required init?(pasteboardPropertyList propertyList: AnyObject, ofType type: String) {
fatalError("\(__FUNCTION__) is not supported")
}
// MARK: NSTextStorage Primitive Methods
// https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/TextStorageLayer/Tasks/Subclassing.html
override var string: String {
return storage.string
}
override func attributesAtIndex(location: Int, effectiveRange range: NSRangePointer) -> [String : AnyObject] {
return storage.attributesAtIndex(location, effectiveRange: range)
}
override func replaceCharactersInRange(range: NSRange, withString str: String) {
beginEditing()
storage.replaceCharactersInRange(range, withString: str)
edited(.EditedCharacters, range: range, changeInLength: (str as NSString).length - range.length)
endEditing()
}
override func setAttributes(attrs: [String : AnyObject]?, range: NSRange) {
beginEditing()
storage.setAttributes(attrs, range: range)
edited(.EditedAttributes, range: range, changeInLength: 0)
endEditing()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment