在 Swift 中如何为字符串中的单个字符添加动画效果

3

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

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

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

我在这里使用了表情符号代码:查找字符串中的字符是否为表情符号?
我不确定如何设置动画。
1个回答

3

我稍微修改了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图

最初的回答已经翻译完成,如有需要请告知。

1
感谢您抽出时间进行翻译 :D - undefined
太棒了! - undefined

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接