Skip to content

Instantly share code, notes, and snippets.

@mrugeshtank
Created January 23, 2020 02:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mrugeshtank/fa0ae78a612a4625052b5e0ed7bc9633 to your computer and use it in GitHub Desktop.
Save mrugeshtank/fa0ae78a612a4625052b5e0ed7bc9633 to your computer and use it in GitHub Desktop.
UITextField with maxLength property
private var __maxLengthsForTextField = [UITextField: Int]()
extension UITextField {
//https://stackoverflow.com/a/43099816/3110026
@IBInspectable var maxLength: Int {
get {
guard let l = __maxLengthsForTextField[self] else {
return 150 // (global default-limit. or just, Int.max)
}
return l
}
set {
__maxLengthsForTextField[self] = newValue
addTarget(self, action: #selector(fix), for: .editingChanged)
}
}
@objc func fix(textField: UITextField) {
if let t = textField.text {
textField.text = String(t.prefix(maxLength))
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment