您可以使用
transition(with:...)
来实现动画效果。例如,在Swift 3及更高版本中,将单词
ipsum
淡化为绿色:
let range = (textView.text as NSString).range(of: "ipsum")
if range.location == NSNotFound { return }
let string = textView.attributedText.mutableCopy() as! NSMutableAttributedString
string.addAttribute(.foregroundColor, value: UIColor.green, range: range)
UIView.transition(with: textView, duration: 1.0, options: .transitionCrossDissolve, animations: {
self.textView.attributedText = string
})
最初,您还询问了有关在此动画期间使文本增长和缩小的内容,这更加复杂。但是您可以搜索文本,找到selectionRects
,对这些视图进行快照,并动画化它们的transform
。例如:
func growAndShrink(_ searchText: String) {
let beginning = textView.beginningOfDocument
guard
let string = textView.text,
let range = string.range(of: searchText),
let start = textView.position(from: beginning, offset: string.distance(from: string.startIndex, to: range.lowerBound)),
let end = textView.position(from: beginning, offset: string.distance(from: string.startIndex, to: range.upperBound)),
let textRange = textView.textRange(from: start, to: end)
else {
return
}
textView.selectionRects(for: textRange)
.forEach { selectionRect in
guard let snapshotView = textView.resizableSnapshotView(from: selectionRect.rect, afterScreenUpdates: false, withCapInsets: .zero) else { return }
snapshotView.frame = view.convert(selectionRect.rect, from: textView)
view.addSubview(snapshotView)
UIView.animate(withDuration: 1, delay: 0, options: .autoreverse, animations: {
snapshotView.transform = CGAffineTransform(scaleX: 1.5, y: 1.5)
}, completion: { _ in
snapshotView.removeFromSuperview()
})
}
}
并且
growAndShrink("consectetaur cillium”)
将产生以下结果:
如果您只是动画文本的颜色,您可能希望先将其渐变为 clear
再将其渐变为所需的颜色(使它更加突出),您可以使用 completion
块:
func animateColor(of searchText: String) {
let range = (textView.text as NSString).range(of: searchText)
if range.location == NSNotFound { return }
let string = textView.attributedText.mutableCopy() as! NSMutableAttributedString
string.addAttribute(.foregroundColor, value: UIColor.clear, range: range)
UIView.transition(with: textView, duration: 0.25, options: .transitionCrossDissolve, animations: {
self.textView.attributedText = string
}, completion: { _ in
string.addAttribute(.foregroundColor, value: UIColor.red, range: range)
UIView.transition(with: self.textView, duration: 0.25, options: .transitionCrossDissolve, animations: {
self.textView.attributedText = string
})
})
}
结果为:
对于Swift的早期版本,请参见此答案的先前修订版本。
transitionWithView
对于颜色起作用。我在示例中放置了它,因为我无法弄清如何缩放字符串中字符的大小 - 因此我放置了我能想到的最接近的示例,即颜色。您能否建议我如何使字母“突出”(放大并缩小)? - Chris