Skip to content

Instantly share code, notes, and snippets.

@hemangshah
Created August 24, 2017 09:44
Show Gist options
  • Save hemangshah/80a9b497d18e9ab736026a22ae725019 to your computer and use it in GitHub Desktop.
Save hemangshah/80a9b497d18e9ab736026a22ae725019 to your computer and use it in GitHub Desktop.
Observe Text changes in UILabel in Swift
class MyLabel: UILabel {
var textWillChange:((_ oldText: String?)->())? = nil
var textDidChange:((_ newText: String?)->())? = nil
override var text: String? {
willSet {
if textWillChange != nil {
textWillChange!(self.text)
}
}
didSet {
if textDidChange != nil {
textDidChange!(self.text)
}
}
}
}
override func viewDidLoad() {
super.viewDidLoad()
//Usage:
let label = MyLabel()
label.textDidChange = { (text) in
print("New Text: \(String(describing: text))")
}
label.textWillChange = { (text) in
print("Old Text: \(String(describing: text))")
}
}
@codekidX
Copy link

Thanks for the tip !

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment