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

标签 swift animation uicollectionview label

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

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

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/

相关文章:

iphone - jQuery插件,类似iphone app页面滑动动画

java - 动画从一个点到另一个点绘制的线

ios - 调整 Collection View 背景和单元格间距的背景颜色和间距

ios - CFNetwork 在 iOS 中使用 swift 崩溃

ios - WKWebView:从 iOS 中的文档文件夹加载内容

ios - 我从 NSUserDefaults 得到的对象(字典)有问题

ios - Swift 可重用细胞图像被重用

html - CSS缩放背景错误

ios - 使用自定义布局时未调用 sizeForItemAt 方法

ios - 关闭 View 时更改值