Created
May 23, 2016 21:43
-
-
Save alexcurylo/d6e3d8ce08540acf90600e1ad46ad027 to your computer and use it in GitHub Desktop.
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
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 | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
this file not work in xcode 10 but it working in xcode 9.3