gpt4 book ai didi

swift - String Swift 中的动画单个字符

转载 作者:搜寻专家 更新时间:2023-11-01 06:51:02 24 4
gpt4 key购买 nike

我们如何为字符串中的单个字符设置动画?即:我有字符串:“嘿👋”。我想通过将其设置为来回旋转来为表情符号设置动画,使其看起来像是在挥手。

为了检测表情符号,我正在使用:

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 }
}

我在这里使用表情符号代码:Find out if Character in String is emoji? .

我不确定如何设置动画

最佳答案

我在 post 中稍微修改了 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()
})
}
}

您可以根据需要修改动画的持续时间和“波浪”的角度。我希望这对您有所帮助!

Gif showing single animated character

关于swift - String Swift 中的动画单个字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57030171/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com