Detect UILabel text change in swift

前端 未结 5 884
情书的邮戳
情书的邮戳 2020-12-25 15:28

Is there a way to get notified when there is a change in a UILabel\'s text or would I be better off using a UITextField with userInteractionE

5条回答
  •  时光说笑
    2020-12-25 15:37

    Swift 5

    If you want to observe text changes in the label and make an animation. You need to create subclass UILabel

    class ObservedLabelAnimate: SpringLabel {
    
        override var text: String? {
            didSet {
                if let text = text {
                    if oldValue != text {
                        animation = "fadeInLeft"
                        duration = 1.2
                        animate()
                    }
                    print("This is oldvalue \(oldValue), and this is the new one \(text)")
                }
            }
        }
    }
    

    for this example, I subclass 'SpringLabel' that inherits from UILabel

    from https://github.com/MengTo/Spring

    Basically it will check if the oldValue and text (new one) is different then the animation will be fired

    To use:

    @IBOutlet weak var label: ObservedLabelAnimate!

提交回复
热议问题