Created
January 23, 2020 02:33
-
-
Save mrugeshtank/fa0ae78a612a4625052b5e0ed7bc9633 to your computer and use it in GitHub Desktop.
UITextField with maxLength property
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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