fields ios swift uitextfield character max

ios - fields - Longitud máxima UITextField



text field ios 11 (14)

Agrega más detalles de @Martin answer

// linked your button here @IBAction func mobileTFChanged(sender: AnyObject) { checkMaxLength(sender as! UITextField, maxLength: 10) } // linked your button here @IBAction func citizenTFChanged(sender: AnyObject) { checkMaxLength(sender as! UITextField, maxLength: 13) } func checkMaxLength(textField: UITextField!, maxLength: Int) { // swift 1.0 //if (count(textField.text!) > maxLength) { // textField.deleteBackward() //} // swift 2.0 if (textField.text!.characters.count > maxLength) { textField.deleteBackward() } }

Cuando he intentado ¿Cómo estableces el número máximo de caracteres que se pueden ingresar en un UITextField usando swift? , Vi que si uso los 10 caracteres, no puedo borrar el personaje también.

Lo único que puedo hacer es cancelar la operación (eliminar todos los caracteres).

¿Alguien sabe cómo no bloquear el teclado (para que no pueda agregar otras letras / símbolos / números, pero puedo usar el retroceso)?


Como los delegados tienen una relación de 1 a 1 y es posible que desee utilizarlo en otro lado por otros motivos, me gusta restringir la longitud del campo de texto agregando este código dentro de su configuración:

required init(coder aDecoder: NSCoder) { super.init(coder: aDecoder)! setup() } required override init(frame: CGRect) { super.init(frame: frame) setup() } func setup() { // your setup... setMaxLength() } let maxLength = 10 private func setMaxLength() { addTarget(self, action: #selector(textfieldChanged(_:)), for: UIControlEvents.editingChanged) } @objc private func textfieldChanged(_ textField: UITextField) { guard let text = text else { return } let trimmed = text.characters.prefix(maxLength) self.text = String(trimmed) }


Debe verificar si la cadena existente más la entrada es mayor que 10.

func textField(textField: UITextField!,shouldChangeCharactersInRange range: NSRange, replacementString string: String!) -> Bool { NSUInteger newLength = textField.text.length + string.length - range.length; return !(newLength > 10) }


He estado usando este protocolo / extensión en una de mis aplicaciones, y es un poco más legible. Me gusta cómo reconoce los espacios vacíos y explícitamente te dice cuando un personaje es un retroceso.

Algunas cosas a considerar:

1.Lo que implemente esta extensión de protocolo necesita especificar un límite de caracteres. Ese será típicamente tu ViewController, pero podrías implementar el límite de caracteres como una propiedad calculada y devolver algo más, por ejemplo, un límite de caracteres en uno de tus modelos.

2. Deberá llamar a este método dentro del método delegado shouldChangeCharactersInRange de su campo de texto. De lo contrario, no podrá bloquear el ingreso de texto al devolver falso, etc.

3. Es probable que desee permitir el retroceso de caracteres a través de. Es por eso que agregué la función adicional para detectar espacios invertidos. Su método shouldChangeCharacters puede verificar esto y devolver ''verdadero'' desde el principio para que siempre permita retrocesos.

protocol TextEntryCharacterLimited{ var characterLimit:Int { get } } extension TextEntryCharacterLimited{ func charactersInTextField(textField:UITextField, willNotExceedCharacterLimitWithReplacementString string:String, range:NSRange) -> Bool{ let startingLength = textField.text?.characters.count ?? 0 let lengthToAdd = string.characters.count let lengthToReplace = range.length let newLength = startingLength + lengthToAdd - lengthToReplace return newLength <= characterLimit } func stringIsBackspaceWith(string:String, inRange range:NSRange) -> Bool{ if range.length == 1 && string.characters.count == 0 { return true } return false } }

Si alguno de ustedes está interesado, tengo un repositorio de Github donde tomé parte de este comportamiento de límite de caracteres y lo coloqué en un marco de iOS. Hay un protocolo que puede implementar para obtener una visualización de límite de caracteres similar a Twitter que le muestra cuánto ha superado el límite de caracteres.

CharacterLimited Framework en Github


Lo hago así:

func checkMaxLength(textField: UITextField!, maxLength: Int) { if (countElements(textField.text!) > maxLength) { textField.deleteBackward() } }

El código funciona para mí. Pero trabajo con el guión gráfico. En Storyboard agrego una acción para el campo de texto en el controlador de vista en la edición modificada .


Si quiere sobrescribir la última letra:

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool { if range.location > 9 { textField.text?.removeLast() } return true }



IBInspectable una solución usando IBInspectable , por lo que puede cambiar el valor de longitud máxima tanto en el constructor de interfaz como programáticamente. Compruébalo aquí


Actualización para Swift 4

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool { guard let text = textField.text else { return true } let newLength = text.count + string.count - range.length return newLength <= 10 }


En Swift 4

Límite de 10 caracteres para el campo de texto y permitir eliminar (retroceso)

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool { if textField == userNameFTF{ let char = string.cString(using: String.Encoding.utf8) let isBackSpace = strcmp(char, "//b") if isBackSpace == -92 { return true } return textField.text!.count <= 9 } return true }


Swift 3

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool { let nsString = NSString(string: textField.text!) let newText = nsString.replacingCharacters(in: range, with: string) return newText.characters.count <= limitCount }


Para Swift 3, pruebe la siguiente implementación de textField(_:shouldChangeCharactersIn:replacementString:) que es parte del protocolo UITextFieldDelegate :

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool { guard let text = textField.text else { return true } let newLength = text.characters.count + string.characters.count - range.length return newLength <= 10 // Bool }

De acuerdo con sus necesidades, sin embargo, puede preferir esta implementación (vea Strings en Swift 2 para más detalles):

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool { guard let text = textField.text else { return true } let newLength = text.utf16.count + string.utf16.count - range.length return newLength <= 10 // Bool }

El siguiente código muestra cómo implementarlo en un UIViewController :

import UIKit class ViewController: UIViewController, UITextFieldDelegate { @IBOutlet weak var textField: UITextField! // Link this to a UITextField in your storyboard let limitLength = 10 override func viewDidLoad() { super.viewDidLoad() textField.delegate = self } func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool { guard let text = textField.text else { return true } let newLength = text.characters.count + string.characters.count - range.length return newLength <= limitLength } }


Here is my version of code. Hope it helps! func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool { let invalidCharacters = NSCharacterSet(charactersInString: "0123456789").invertedSet if let range = string.rangeOfCharacterFromSet(invalidCharacters, options: nil, range:Range<String.Index>(start: string.startIndex, end: string.endIndex)) { return false } if (count(textField.text) > 10 && range.length == 0) { self.view.makeToast(message: "Amount entry is limited to ten digits", duration: 0.5, position: HRToastPositionCenter) return false } else { } return true }


func checkMaxLength(textField: UITextField!, maxLength: Int) { if (textField.text!.characters.count > maxLength) { textField.deleteBackward() } }

un pequeño cambio para IOS 9