在UILabel中逐个打印属性字符串字符

时间:2017-11-16 22:05:20

标签: ios swift animation nsattributedstring nstextstorage

我有一个自定义UILabel类,允许我将tapGestureRecognizers附加到字符串的特定部分。现在,我正在尝试为UILabel的文本设置动画,以便一次打印一个字符。我的代码似乎是一次向TextStorage添加一个字符,但文本同时显示所有字符,没有动画。是否一次向TextStorage添加一个字符的错误方法?感谢

class CustomLabel: UILabel {

    let layoutManager = NSLayoutManager()
    let textContainer = NSTextContainer(size: CGSize.zero)
    var textStorage = NSTextStorage() {
        didSet {
            textStorage.addLayoutManager(layoutManager)
        }
    }
    var onCharacterTapped: ((_ label: UILabel, _ characterIndex: Int) -> Void)?

    let tapGesture = UITapGestureRecognizer()

    override var attributedText: NSAttributedString? {
        didSet {
            if let attributedText = attributedText {

                DispatchQueue.main.async {

                    for (index, char) in attributedText.string.characters.enumerated() {

                        DispatchQueue.main.asyncAfter(deadline: .now() + 0.5 * Double(index)) {
                            print("character ch is: \(char) at index: \(index)")
                            let text = NSAttributedString(string: String(char))
                            self.textStorage = NSTextStorage(attributedString: text)
                        }
                    }
                }

            } else {
                textStorage = NSTextStorage()
            }
        }
    }
}

0 个答案:

没有答案