Skip to content

Instantly share code, notes, and snippets.

@alexcurylo
Created May 23, 2016 21:43
Show Gist options
  • Save alexcurylo/d6e3d8ce08540acf90600e1ad46ad027 to your computer and use it in GitHub Desktop.
Save alexcurylo/d6e3d8ce08540acf90600e1ad46ad027 to your computer and use it in GitHub Desktop.
import UIKit
// 1
private var maxLengths = [UITextField: Int]()
// 2
extension UITextField {
// 3
@IBInspectable var maxLength: Int {
get {
// 4
guard let length = maxLengths[self] else {
return Int.max
}
return length
}
set {
maxLengths[self] = newValue
// 5
addTarget(
self,
action: #selector(limitLength),
forControlEvents: UIControlEvents.EditingChanged
)
}
}
func limitLength(textField: UITextField) {
// 6
guard let prospectiveText = textField.text
where prospectiveText.characters.count > maxLength else {
return
}
let selection = selectedTextRange
// 7
text = prospectiveText.substringWithRange(
Range<String.Index>(prospectiveText.startIndex ..< prospectiveText.startIndex.advancedBy(maxLength))
)
selectedTextRange = selection
}
}
@jignesh133
Copy link

this file not work in xcode 10 but it working in xcode 9.3

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