Detect UILabel text change in swift

前端 未结 5 886
情书的邮戳
情书的邮戳 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:52

    For Swift 3.2 and later, the preferred method is to use a closure-based observer:

    @IBOutlet public weak var label: UILabel!
    
    var textObserver: NSKeyValueObservation?
    
    func someAppropriateFunction() {
      ...
      textObserver = label.observe(\.text) { [weak self] (label, observedChange) in
        self?.updateStuff()
      }
    }
    

    The closure will pass you the label instance and an NSKeyValueObservedChange that includes the following properties:

      indexes: IndexSet?
      isPrior: Bool
      kind: NSKeyValueObservedChange.Kind
      newValue: Value?
      oldValue: Value?
    

提交回复
热议问题