Skip to content

Instantly share code, notes, and snippets.

@edudnyk
Last active July 30, 2019 21:58
Show Gist options
  • Save edudnyk/cc275cc3acac6a88ff920408506e3af1 to your computer and use it in GitHub Desktop.
Save edudnyk/cc275cc3acac6a88ff920408506e3af1 to your computer and use it in GitHub Desktop.
var interpolatedFromAttributedText : NSAttributedString? {
get {
return fill(withInterpolatedAttributes: fromAttributedText)
}
}
var interpolatedToAttributedText : NSAttributedString? {
get {
if toAttributedText != nil {
return fill(withInterpolatedAttributes: toAttributedText!)
}
return nil
}
}
private func fill(withInterpolatedAttributes attributedString: NSAttributedString?)->NSAttributedString {
let mutableInterpolatedAttributedText = attributedString != nil ?
NSMutableAttributedString(attributedString: attributedString!) :
NSMutableAttributedString()
mutableInterpolatedAttributedText.beginEditing()
interpolatedAttributeStates.enumerateKeysAndObjects
{ (keyInAttrStates, objInAttrStates, stopInAttrStates) in
guard let attrValuePerRangeString = objInAttrStates as? NSDictionary,
let attrStrKeyRawValue = keyInAttrStates as? String else { return }
attrValuePerRangeString.enumerateKeysAndObjects { (keyInRange, objInRange, stopInRange) in
guard let rangeString = keyInRange as? String else { return }
let range = NSRangeFromString(rangeString)
if range.location < mutableInterpolatedAttributedText.length {
let key = NSAttributedString.Key(rawValue: attrStrKeyRawValue)
let range = NSMakeRange(range.location,
min(mutableInterpolatedAttributedText.length -
range.location,
range.length))
if let decodedObject = LKTextDidChangeAction.decodeAttribute(from: objInRange as AnyObject,
forAttributedStringKey: key) {
mutableInterpolatedAttributedText.addAttribute(key,
value: decodedObject,
range: range)
} else {
mutableInterpolatedAttributedText.removeAttribute(key, range: range)
}
}
}
}
mutableInterpolatedAttributedText.endEditing()
return mutableInterpolatedAttributedText
}
private static func decodeAttribute(from object: AnyObject?,
forAttributedStringKey key: NSAttributedString.Key)->AnyObject? {
guard let dictionary = object as? NSDictionary else { return object }
switch key {
case .font:
return UIFont.lk_dictDecode(dictionaryRepresentation: dictionary)
case .foregroundColor,
.backgroundColor,
.strokeColor,
.underlineColor,
.strikethroughColor:
return UIColor.lk_dictDecode(dictionaryRepresentation: dictionary)
case .paragraphStyle:
return NSParagraphStyle.lk_dictDecode(dictionaryRepresentation: dictionary)
case .shadow:
return NSShadow.lk_dictDecode(dictionaryRepresentation: dictionary)
default:
return object
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment