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
Use below extension for
UITextField
andUITextView
character limits.You can set limit below.
Got it down to 1 line of code :)
Set your text view's delegate to "self" then add the
<UITextViewDelegate>
in your .h and the following code in your .m .... you can adjust the number "7" to be whatever you want your MAXIMUM number of characters to be.This code accounts for typing new characters, deleting characters, selecting characters then typing or deleting, selecting characters and cutting, pasting in general, and selecting characters and pasting.
Done!
Alternatively, another cool way to write this code with bit-operations would be
I created this UITextFieldLimit subclass:
Grab the
UITextFieldLimit.h
andUITextFieldLimit.m
from this GitHub repository:https://github.com/JonathanGurebo/UITextFieldLimit
and begin to test!
Mark your storyboard-created UITextField and link it to my subclass using the Identity Inspector:
Then you can link it to an IBOutlet and set the limit(default is 10).
Your ViewController.h file should contain: (if you wan't to modify the setting, like the limit)
Your ViewController.m file should
@synthesize textFieldLimit
.Set the text length limit in your ViewController.m file:
Hope the class helps you. Good luck!
To make it work with cut & paste of strings of any length, I would suggest changing the function to something like:
Thank you august! (Post)
This is the code that I ended up with which works:
Other answers do not handle the case where user can paste a long string from clipboard. If I paste a long string it should just be truncated but shown. Use this in your delegate: