How can I set the maximum amount of characters in a UITextField
on the iPhone SDK when I load up a UIView
?
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.
import Foundation
extension String {
func containsCharactersIn(matchCharacters: String) -> Bool {
let characterSet = NSCharacterSet(charactersInString: matchCharacters)
return self.rangeOfCharacterFromSet(characterSet) != nil
}
func containsOnlyCharactersIn(matchCharacters: String) -> Bool {
let disallowedCharacterSet = NSCharacterSet(charactersInString: matchCharacters).invertedSet
return self.rangeOfCharacterFromSet(disallowedCharacterSet) == nil
}
func doesNotContainCharactersIn(matchCharacters: String) -> Bool {
let characterSet = NSCharacterSet(charactersInString: matchCharacters)
return self.rangeOfCharacterFromSet(characterSet) == nil
}
func isNumeric() -> Bool
{
let scanner = NSScanner(string: self)
scanner.locale = NSLocale.currentLocale()
return scanner.scanDecimal(nil) && scanner.atEnd
}
}
Now save the class.....
Usage..
Now goto your viewController.swift class and make your textfield's outlets as..
@IBOutlet weak var contactEntryTxtFld: UITextField! //First textfield
@IBOutlet weak var contactEntryTxtFld2: UITextField! //Second textfield
Now goto the textfield's shouldChangeCharactersInRange method and use like the following.
func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
if string.characters.count == 0 {
return true
}
let latestText = textField.text ?? ""
let checkAbleText = (latestText as NSString).stringByReplacingCharactersInRange(range, withString: string)
switch textField {
case contactEntryTxtFld:
return checkAbleText.containsOnlyCharactersIn("0123456789") && prospectiveText.characters.count <= 5
case contactEntryTxtFld2:
return checkAbleText.containsOnlyCharactersIn("0123456789") && prospectiveText.characters.count <= 5
default:
return true
}
}
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 created this UITextFieldLimit subclass:
Grab the UITextFieldLimit.h
and UITextFieldLimit.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)
#import "UITextFieldLimit.h"
/.../
@property (weak, nonatomic) IBOutlet UITextFieldLimit *textFieldLimit; // <--Your IBOutlet
Your ViewController.m file should @synthesize textFieldLimit
.
Set the text length limit in your ViewController.m file:
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
[textFieldLimit setLimit:25];// <-- and you won't be able to put more than 25 characters in the TextField.
}
Hope the class helps you. Good luck!
The best way would be to set up a notification on the text changing. In your -awakeFromNib
of your view controller method you'll want:
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(limitTextField:) name:@"UITextFieldTextDidChangeNotification" object:myTextField];
Then in the same class add:
- (void)limitTextField:(NSNotification *)note {
int limit = 20;
if ([[myTextField stringValue] length] > limit) {
[myTextField setStringValue:[[myTextField stringValue] substringToIndex:limit]];
}
}
Then link up the outlet myTextField
to your UITextField
and it will not let you add any more characters after you hit the limit. Be sure to add this to your dealloc method:
[[NSNotificationCenter defaultCenter] removeObserver:self name:@"UITextFieldTextDidChangeNotification" object:myTextField];
now how many characters u want just give values
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
NSUInteger newLength = [textField.text length] + [string length] - range.length;
return (newLength > 25) ? NO : YES;
}
I simulate the actual string replacement that's about to happen to calculate that future string's length:
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
NSString *newString = [textField.text stringByReplacingCharactersInRange:range withString:string];
if([newString length] > maxLength)
return NO;
return YES;
}
Using Interface builder you can link and get the event for "Editing changed" in any of your function. Now there you can put check for the length
- (IBAction)onValueChange:(id)sender
{
NSString *text = nil;
int MAX_LENGTH = 20;
switch ([sender tag] )
{
case 1:
{
text = myEditField.text;
if (MAX_LENGTH < [text length]) {
myEditField.text = [text substringToIndex:MAX_LENGTH];
}
}
break;
default:
break;
}
}