swift - 在字符串 Swift 中为单个字符设置动画
问题描述
我们如何为字符串中的单个字符设置动画?即:我有字符串:“嘿”。我想通过将表情符号设置为来回旋转来为表情符号设置动画,使其看起来像在挥动。
为了检测表情符号,我正在使用:
extension String {
// Not needed anymore in swift 4.2 and later, using `.count` will give you the correct result
var glyphCount: Int {
let richText = NSAttributedString(string: self)
let line = CTLineCreateWithAttributedString(richText)
return CTLineGetGlyphCount(line)
}
var isSingleEmoji: Bool {
return glyphCount == 1 && containsEmoji
}
var containsEmoji: Bool {
return unicodeScalars.contains { $0.isEmoji }
}
我在这里使用表情符号代码:找出字符串中的字符是否是表情符号?.
我不确定如何设置动画
解决方案
我在这篇文章中对 Rob 的这个出色的答案进行了非常细微的修改。
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
animateEmojiBackandForth("")
}
func animateEmojiBackandForth (_ 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(rotationAngle: CGFloat( CGFloat.pi / 4))
}, completion: { _ in
snapshotView.removeFromSuperview()
})
}
}
您可以根据需要修改动画的持续时间和“波浪”的角度。我希望这可以帮到你!
推荐阅读
- php - 如何使用两个插入查询从复选框循环两个值
- python - 如何在 python 中并行化包含发布请求 API 调用的 for 循环?
- session - express session值自动销毁
- excel - Excel 日期问题 - 将 Adobe PDF 保存为 XML 2003
- msal - msal angular 得到 ERROR 错误:未捕获(承诺中):错误:无法匹配任何路由。URL 段:'id_token'
- ajax - jQuery [attribute!=value] 选择器
- java - ThreadMXBean.getThreadCpuTime 返回 0
- c++ - 为表示一个或多个操作的 C++ 函数查找 int 参数的类型安全替换
- git - 在drupal 8中安装模块时作曲家抛出git错误
- typescript - 将类型分配给可能不需要解析的 JSON 类型