【问题标题】:Animate Single Character in String Swift在字符串 Swift 中为单个字符设置动画
【发布时间】:2019-07-14 18:40:04
【问题描述】:

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

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

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?

我不确定如何设置动画

【问题讨论】:

    标签: swift animation uicollectionview label


    【解决方案1】:

    我在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()
                    })
            }
        }
    

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

    【讨论】:

    • 感谢您花时间翻译:D
    • 这太棒了!
    猜你喜欢
    • 2022-01-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-31
    相关资源
    最近更新 更多