首页 > 解决方案 > 在字符串 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 }
}

我在这里使用表情符号代码:找出字符串中的字符是否是表情符号?.

我不确定如何设置动画

标签: swiftanimationuicollectionviewlabel

解决方案


我在这篇文章中对 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


推荐阅读