Skip to content

Instantly share code, notes, and snippets.

@rajohns08
Last active November 3, 2015 13:22
Show Gist options
  • Save rajohns08/79d9db61e26370365896 to your computer and use it in GitHub Desktop.
Save rajohns08/79d9db61e26370365896 to your computer and use it in GitHub Desktop.
iOS / Swift - Put a max number of characters for UITextField
import UIKit
let maxNumCharacters = 5
class ViewController: UIViewController {
@IBOutlet weak var textField: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
}
}
extension ViewController: UITextFieldDelegate {
func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
let newLength = count(textField.text) + count(string) - range.length
return newLength <= maxNumCharacters
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment