Skip to content

Instantly share code, notes, and snippets.

@edudnyk
Last active July 29, 2019 21:09
Show Gist options
  • Save edudnyk/f57e504b56166bf053f385baaba3e78a to your computer and use it in GitHub Desktop.
Save edudnyk/f57e504b56166bf053f385baaba3e78a to your computer and use it in GitHub Desktop.
var animations = [CABasicAnimation]()
let rootAttributesKey = keyPath(\LKLabelLayer.currentTextDidChangeAnimation?
.interpolatedAttributeStates)
type(of: self).attributedStringKeys.forEach { (attributeRawValue) in
var shorterTextValue : AnyObject? = nil
let attributedStringKey = NSAttributedString.Key(rawValue: attributeRawValue)
let swapped = self.toAttributedText?.length ?? 0 > self.fromAttributedText?.length ?? 0
let longerText = swapped ? self.toAttributedText : self.fromAttributedText
let shorterText = swapped ? self.fromAttributedText : self.toAttributedText
longerText?.enumerateAttribute(attributedStringKey,
in: NSMakeRange(0, longerText?.length ?? 0),
options: [],
using: { (longerTextValue, longerTextRange, longerTextStop) in
let isLastLongerTextRange = NSMaxRange(longerTextRange) == longerText?.length
if shorterText != nil && longerTextRange.location < shorterText!.length {
let toEnumerationRange = isLastLongerTextRange ?
NSMakeRange(longerTextRange.location,
shorterText!.length - longerTextRange.location) :
longerTextRange
shorterText!.enumerateAttribute(attributedStringKey,
in: toEnumerationRange,
options: [],
using: { (value, shorterTextRange, shorterTextStop) in
shorterTextValue = value as AnyObject
if (longerTextValue != nil || shorterTextValue != nil) &&
!(longerTextValue as AnyObject).isEqual(shorterTextValue) {
let fromValue = swapped ? shorterTextValue : longerTextValue
let toValue = swapped ? longerTextValue : shorterTextValue
animations.append(contentsOf:
type(of: self).animationsForAttributeDiff(
forRootKey:rootAttributesKey,
attributedStringKey: attributedStringKey,
fromValue: fromValue,
toValue: toValue,
in: shorterTextRange,
attributeStates: self.interpolatedAttributeStates,
duration: duration))
}
})
if (shorterText == nil || NSMaxRange(longerTextRange) > shorterText!.length) &&
(longerTextValue != nil || shorterTextValue != nil) &&
!(longerTextValue as AnyObject).isEqual(shorterTextValue) {
let fromValue = swapped ? shorterTextValue : longerTextValue
let toValue = swapped ? longerTextValue : shorterTextValue
animations.append(contentsOf:
type(of: self).animationsForAttributeDiff(
forRootKey: rootAttributesKey,
attributedStringKey: attributedStringKey,
fromValue: fromValue,
toValue: toValue,
in: longerTextRange,
attributeStates: self.interpolatedAttributeStates,
duration: duration))
}
}
})
}
if animations.count > 0 {
self.animations = animations
self.duration = duration
self.timingFunction = CAMediaTimingFunction(name: .easeInEaseOut )
textLayer.add(self, forKey: keyPath(\LKLabelLayer.attributedText))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment