I use this protocol / extension in one of my applications and it is a little readable. I love the way it recognizes backspaces and explicitly tells you when a character is a backspace.
Some things to consider:
1. In any case, this protocol extension should indicate a character restriction. This will usually be your ViewController, but you can implement the character constraint as a computed property and return something else, such as a character limit on one of your models.
2. You will need to call this method inside your text box shouldChangeCharactersInRange delegate method. Otherwise, you cannot block text input by returning false, etc.
3. You probably want to allow reverse characters. . So I added an extra function to detect backspaces. Your shouldChangeCharacters method can verify this and return true at an early stage so that you always allow backspaces.
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 } }
If any of you are interested, I have a Github repository where I took some of these character behavior rules and put it on iOS. There, a protocol that you can implement to display the character limit on Twitter shows how much you went above the character limit.
CharacterLimited Framework on Github
Theo Bendixson Sep 10 '16 at 1:43 on 2016-09-10 13:43
source share