Created
September 19, 2018 09:25
-
-
Save daoseng33/8fccaa285de093a4623ddf4ae68f2c1a to your computer and use it in GitHub Desktop.
Let you set UITextField max length in storyboard or xib
This file contains 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
// Set textfield max length | |
private var __maxLengths = [UITextField: Int]() | |
extension UITextField { | |
@IBInspectable var maxLength: Int { | |
get { | |
guard let l = __maxLengths[self] else { | |
return Int.max // (global default-limit. or just, Int.max) | |
} | |
return l | |
} | |
set { | |
__maxLengths[self] = newValue | |
addTarget(self, action: #selector(fix), for: .editingChanged) | |
} | |
} | |
@objc func fix(textField: UITextField) { | |
let t = textField.text | |
textField.text = t?.safelyLimitedTo(length: maxLength) | |
} | |
} | |
extension String { | |
func safelyLimitedTo(length n: Int) -> String { | |
let c = self | |
if c.count <= n { return self } | |
return String(Array(c).prefix(upTo: n)) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment