number length characters ios swift uitextfield uitextview

ios - characters - swift set text field max length



Estableciendo el número máximo de caracteres de `UITextView` y `UITextField` (7)

Me gustaría establecer un número máximo de caracteres que se pueden escribir tanto en un UITextView como en un UITextField . Este número se mostrará en una pequeña etiqueta (para referencia del usuario, Estilo de Twitter).


Actualizar Swift 4.X

func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool { let newText = (textView.text as NSString).replacingCharacters(in: range, with: text) let numberOfChars = newText.count return numberOfChars < 10 // 10 Limit Value }

Probar esto:

func textView(textView: UITextView, shouldChangeTextInRange range: NSRange, replacementText text: String) -> Bool { let newText = (textView.text as NSString).stringByReplacingCharactersInRange(range, withString: text) let numberOfChars = newText.characters.count // for Swift use count(newText) return numberOfChars < 10; }


Probar esto:-

func textView(textView: UITextView, shouldChangeTextInRange range: NSRange, replacementText text: String) -> Bool { print("chars /(textView.text.characters.count) /( text)") if(textView.text.characters.count > 20 && range.length == 0) { print("Please summarize in 20 characters or less") return false; } return true; }


Swift 4, Xcode 9.1 GM

func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool { adjustFrames() return textView.text.count + (text.count - range.length) <= 200 }


SWIFT 4

func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool { let newText = (textView.text as NSString).replacingCharacters(in: range, with: text) return newText.count < 10 }


Swift 3.0

Simplemente anule esta función UITextFieldDelegate, establezca la variable de límite de caracteres deseada y estará listo:

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


Swift 4 / Xcode 9.1

func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool { let currentText = textView.text ?? "" guard let stringRange = Range(range, in: currentText) else { return false } let changedText = currentText.replacingCharacters(in: stringRange, with: text) return changedText.count <= 399 // Pass your character count here }


Swift 4:

func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool { let newText = (textView.text as NSString).replacingCharacters(in: range, with: text) return newText.count <= 70 }