Skip to content

Commit 1c5b007

Browse files
committed
implement substring/insert/append
1 parent 22654b0 commit 1c5b007

File tree

1 file changed

+21
-3
lines changed

1 file changed

+21
-3
lines changed

Foundation/NSAttributedString.swift

+21-3
Original file line numberDiff line numberDiff line change
@@ -88,7 +88,10 @@ open class NSAttributedString: NSObject, NSCopying, NSMutableCopying, NSSecureCo
8888
}
8989

9090
/// Returns an NSAttributedString object consisting of the characters and attributes within a given range in the receiver.
91-
open func attributedSubstring(from range: NSRange) -> NSAttributedString { NSUnimplemented() }
91+
open func attributedSubstring(from range: NSRange) -> NSAttributedString {
92+
let attributedSubstring = CFAttributedStringCreateWithSubstring(kCFAllocatorDefault, _cfObject, CFRange(range))
93+
return unsafeBitCast(attributedSubstring, to: NSAttributedString.self)
94+
}
9295

9396
/// Returns the attributes for the character at a given index, and by reference the range over which the attributes apply.
9497
open func attributes(at location: Int, longestEffectiveRange range: NSRangePointer?, in rangeLimit: NSRange) -> [NSAttributedStringKey : Any] {
@@ -339,11 +342,26 @@ open class NSMutableAttributedString : NSAttributedString {
339342
}
340343

341344
open func insert(_ attrString: NSAttributedString, at loc: Int) {
342-
NSUnimplemented()
345+
mutableString.insert(attrString.string, at: loc)
346+
347+
let fullStringRange = NSRange(location: 0, length: attrString._string.length)
348+
attrString.enumerateAttributes(in: fullStringRange) { attribute, range, _ in
349+
var rangeAfterInserting = range
350+
rangeAfterInserting.location += loc
351+
addAttributes(attribute, range: rangeAfterInserting)
352+
}
343353
}
344354

345355
open func append(_ attrString: NSAttributedString) {
346-
NSUnimplemented()
356+
let lengthBeforeAppending = string.length
357+
mutableString.append(attrString.string)
358+
359+
let fullStringRange = NSRange(location: 0, length: attrString._string.length)
360+
attrString.enumerateAttributes(in: fullStringRange) { attribute, range, _ in
361+
var rangeAfterAppending = range
362+
rangeAfterAppending.location += lengthBeforeAppending
363+
addAttributes(attribute, range: rangeAfterAppending)
364+
}
347365
}
348366

349367
open func deleteCharacters(in range: NSRange) {

0 commit comments

Comments
 (0)