How can I set the maximum amount of characters in a UITextField
on the iPhone SDK when I load up a UIView
?
相关问题
- CALayer - backgroundColor flipped?
- Core Data lightweight migration crashes after App
- How can I implement password recovery in an iPhone
- State preservation and restoration strategies with
- “Zero out” sensitive String data in Swift
相关文章
- 现在使用swift开发ios应用好还是swift?
- UITableView dragging distance with UIRefreshContro
- TCC __TCCAccessRequest_block_invoke
- Where does a host app handle NSExtensionContext#co
- xcode 4 garbage collection removed?
- Xcode: Is there a way to change line spacing (UI L
- Unable to process app at this time due to a genera
- Swift - hide pickerView after value selected
I did this in Swift for an 8 character limit when using a number pad.
I had to test for string != "" to allow the delete button to work on the number pad, otherwise it wouldn't allow deleting characters in the text field after it reached its max.
I have implemented a UITextField Extension to add a maxLength property to it.
It's based on Xcode 6 IBInspectables, so you can set the maxLength limit on the Interface builder.
Here is the implementation:
Swift 2.0 +
First of all create a class for this process. Lets call it StringValidator.swift.
Then just paste the following code inside it.
Now save the class.....
Usage..
Now goto your viewController.swift class and make your textfield's outlets as..
Now goto the textfield's shouldChangeCharactersInRange method and use like the following.
Don't forget to set the delegate protocol/methods of textfields.
Let me explain about this... I am using the simple extension process of string which I wrote inside an another class. Now I am just calling those extension methods from another class where I need them by adding check and maximum value.
Features...
Types...
containsOnlyCharactersIn //Accepts only Characters.
containsCharactersIn //Accepts combination of characters
doesNotContainsCharactersIn //Will not accept characters
Hope this helped.... Thanks..
I have open sourced a UITextField subclass, STATextField, that offers this functionality (and much more) with its
maxCharacterLength
property.This is the correct way to handle max length on UITextField, it allows the return key to exit the resign the textfield as first responder and lets the user backspace when they reach the limit
Use this code here RESTRICTED_LENGTH is length you want to restrict for textfield.