Good Night,
I have a text box created, how do I set a maximum of characters that can be written to it? (it has to accept any type of character)
Good Night,
I have a text box created, how do I set a maximum of characters that can be written to it? (it has to accept any type of character)
Set the delegate of UITextField
to an object of your own and implements the textField shouldChangeCharactersInRange
method.
Example:
class ViewController: UIViewController, UITextFieldDelegate {
let maxCharCount = 3
@IBOutlet weak var textField: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
self.textField.delegate = self
}
func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
return textField.text!.characters.count + string.characters.count <= self.maxCharCount
}
}
This code does not address the case of the user pasting text into the textfield that goes beyond the maximum number (the way it is, it will not), but you can already have an idea how to do it.
You can create your own text box by subclassing the UITextField as follows:
@IBDesignable
class LimitedLengthField: UITextField {
@IBInspectable var maxLength: Int = 3 // determine o limite máximo de characters para a sua caixa de texto
var stringValue: String { return text ?? "" }
override func awakeFromNib() {
super.awakeFromNib()
keyboardType = .ASCIICapable // escolha o teclado padrao para a sua caixa de texto
addTarget(self, action: #selector(editingChanged), forControlEvents: .EditingChanged)
editingChanged(self)
}
func editingChanged(sender: UITextField) {
sender.text = String(stringValue.characters.prefix(maxLength))
}
}