Skip to content

Instantly share code, notes, and snippets.

@dneprDroid
Last active May 30, 2018 20:28
Show Gist options
  • Save dneprDroid/90fee55614ce903ddaa7ac0cd24787a4 to your computer and use it in GitHub Desktop.
Save dneprDroid/90fee55614ce903ddaa7ac0cd24787a4 to your computer and use it in GitHub Desktop.
UITextField+MaxTextLength Swift 4
import UIKit
private var _UITextField_maxTextLength = "_UITextField_maxTextLength"
extension UITextField {
@IBInspectable
var maxTextLength:Int {
get {
return objc_getAssociatedObject(self,
&_UITextField_maxTextLength) as? Int ?? .max
}
set {
if objc_getAssociatedObject(self, &_UITextField_maxTextLength) != nil {
objc_setAssociatedObject(self, &_UITextField_maxTextLength,
newValue, .OBJC_ASSOCIATION_ASSIGN)
return
}
addTarget(self, action: #selector(__textChanged), for: .editingChanged)
objc_setAssociatedObject(self, &_UITextField_maxTextLength,
newValue, .OBJC_ASSOCIATION_ASSIGN)
}
}
@objc private func __textChanged() {
let maxCount = maxTextLength
if let text = text,
text.count > maxCount {
let endIndex = text.index(text.startIndex, offsetBy: maxCount)
self.text = String(text[..<endIndex])
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment