Maximum limit of a text box - Swift

Asked

Viewed 489 times

2

Goodnight,

I have a text box created, how do I set a maximum of characters that can be written on it ? (she has to accept any kind of character)

2 answers

1

Defines the delegate of the UITextField for an object of yours and implements the method textField shouldChangeCharactersInRange.

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 treat the case of the user pasting a text in the textfield that passes the maximum number (the way it is, it will not let), but you can already have an idea of how to do.

0

You can create your own Uitextfield subclassing text box 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))
    }
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.