I\'m making an iOS app that has a UITextView. When closing a parenthesis in that UITextView, I want to highlight to the user which opening parenthesis it pairs to. So far I\
Another solution which works for me (Swift 4) is to generate multiple attributed strings, assign one to label and then replace the content (attributedText
) inside transition animation block. For example:
// MARK: Extension util which generates NSAttributedString by text,font,color,backgroundColor
extension NSAttributedString {
class func generate(from text: String, font: UIFont = UIFont.systemFont(ofSize: 16), color: UIColor = .black, backgroundColor: UIColor = .clear) -> NSAttributedString {
let atts: [NSAttributedStringKey : Any] = [.foregroundColor : color, .font : font, .backgroundColor : backgroundColor]
return NSAttributedString(string: text, attributes: atts)
}
}
// MARK: Sentence
let string1 = "Hi, i'm "
let string2 = "Daniel"
// MARK: Generate highlighted string
let prefixAttString = NSAttributedString.generate(from: string1)
let highlightedSuffixAttString = NSAttributedString.generate(from: string2, backgroundColor: .red)
let highlightedString = NSMutableAttributedString()
highlightedString.append(prefixAttString)
highlightedString.append(highlightedSuffixAttString)
// MARK: Generate regular string (Same prefix, different suffix)enter image description here
let regularSuffixAttString = NSAttributedString.generate(from: string2)
let regularString = NSMutableAttributedString()
regularString.append(prefixAttString)
regularString.append(regularSuffixAttString)
self.view.addSubview(label)
label.attributedText = regularString
// UIViewAnimationOptions.transitionCrossDissolve is necessary.
UIView.transition(with: self.label, duration: 4, options: [.transitionCrossDissolve], animations: {
self.label.attributedText = highlightedString
}, completion: nil)
}
Don't forget to use .transitionCrossDissolve
in the animation options.