How to set max string length for UIAlertView text field - objective-c

How can I set the max string length for a textfield created within a UIAlertView? I am using Xcode 4.5 and building the app on 10.8 (OS X) Currently I have UIAlertView that launches when the user clicks a button. The user will scan their RFID badge, and I want the input textfield of the UIAlertView to be limited to 10 (ten) characters so the user can't fudge association process.

You can check the length of the text in the delegate method of the textField:
textField:shouldChangeCharactersInRange:replacementString:
And return NO if you don't want to change.
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
if (textField.text.length - range.length + string.length > 10) {
return NO;
}
return YES;
}

Looks like the above answer is almost right.
When typing single characters, range.length (for this method) appears to always be zero, while the location increments.
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
NSLog(#"Range: %#", NSStringFromRange(range));
return ( range.location < 10 );
}
edit: length would probably be longer if you doing something other than single-character typing, i.e. pasting a line, etc.

Related

When I put a value in my third text box that time I am getting automatically a value in my second text box with multiply by 10

When I put a value in my third text box that time I am getting automatically a value in my second text box with multiply by 10 but I do not want to change that value which is appear in second text box.
Following is my code and method and I am sharing two screen one is without error and second is with error.this is with error
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
_hourlyrate.text=[NSString stringWithFormat:#"%.2f",[_avgsalary.text doubleValue]/208 ];
_totalMcost.text=[NSString stringWithFormat:#"%.2f",[_hourlyrate.text doubleValue]*[_pepinMeeting.text doubleValue]*[_hoursOfmeeting.text doubleValue]];
NSLog(#"avg: %#",_totalMcost.text);
return YES;
}
When you try to access textfield.text in shouldChangeCharectersInRange method, it will give you the old value before replacing the text.
To get the updated value place this code in
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
double hourlyRateValue = 0.0;
if (textfield == _hourlyrate) {
hourlyRateValue = [textField.text stringByReplacingCharactersInRange:range withString:string] doubleValue]; // Use this value for calculation
}
return YES;
}
Please note that I have written this code in plain text editor. Check the syntax.

How to find a particular text in UITextField?

In my iPhone app I have a UITextField ans text field value is being taken into an NSString, I want to find if a particular character " is typed in that
How can I do that?
UITextField *textField;
NSString *String=textField.text;
-(IBAction)FindCharecter:(id)sender
{
// if String Contain ",then i wish to print #"Found symbol"
}
UITextField *textField;
NSString *string=textField.text;
if ([string rangeOfString:#"\""].location == NSNotFound) {
NSLog(#"string does not \"");
} else {
NSLog(#"string contains \"");
}
check this
Try This:
-(IBAction)FindCharecter:(id)sender
{
// if String Contain ",then i wish to print #"Found symbol"
if ([String rangeOfString:#"\""].location != NSNotFound) {
NSLog(#"Found");
}
else{
NSLog(#"Not Found");
}
}
Implement the following delegate of UITextField
-(NSString *)ValidateSearchString:(NSString *) aString{
NSCharacterSet * set = [[NSCharacterSet characterSetWithCharactersInString:#"YourString"] invertedSet];
if ([aString rangeOfCharacterFromSet:set].location != NSNotFound) {
return #"Not Found";
}
return #"Found";;
}
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
NSLog("particular character %#",[self ValidateSearchString:string]);
// string will contain the particular character typed;
return YES;
}
You need to confirm and implement UITextFieldDelegate protocol.
1) If you want to check for a pattern on the go (when user typing itself), you need to implement
- (BOOL)textField:(UITextField *)textField
shouldChangeCharactersInRange:(NSRange)range
replacementString:(NSString *)string
2) If you want to check when user completed typing, you may want to implement
- (void)textFieldDidEndEditing:(UITextField *)textField
Now to do the actual comparison process
if([textFieldString rangeOfString:#"YOUR_COMPARISON_STRING"].location == NSNotFound){
//your pattern is not typed yet
}else{
//There it is..
}
You can use shouldChangeCharactersInRange delegate method for this.
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
if([string isEqualToString:#"\""])
{
NSLog(#"Entered \" ");
}
}
Or you can use: rangeOfString of NSString class.
if ([textField.text rangeOfString:#"\""].location == NSNotFound)
{
NSLog(#"Entered \" ");
}
For reference:
textField:shouldChangeCharactersInRange:replacementString:
Asks the delegate if the specified text should be changed.
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
Parameters
textField
The text field containing the text.
range
The range of characters to be replaced
string
The replacement string.
Return Value
YES if the specified text range should be replaced; otherwise, NO to
keep the old text. Discussion
The text field calls this method whenever the user types a new
character in the text field or deletes an existing character.
Availability
Available in iOS 2.0 and later.
UITextFieldDelegate
rangeOfString:
Finds and returns the range of the first occurrence of a given string
within the receiver.
- (NSRange)rangeOfString:(NSString *)aString
Parameters
aString
The string to search for. This value must not be nil.
Important: Raises an NSInvalidArgumentException if aString is nil.
Return Value
An NSRange structure giving the location and length in the receiver of
the first occurrence of aString. Returns {NSNotFound, 0} if aString is
not found or is empty (#"").
Discussion
Invokes rangeOfString:options: with no options.
This method detects all invalid ranges (including those with negative
lengths). For applications linked against OS X v10.6 and later, this
error causes an exception; for applications linked against earlier
releases, this error causes a warning, which is displayed just once
per application execution. Availability
Declared In NSString.h
Declared In UITextField.h
NSString Class

Character limit for multiple uitextfields

I'm a fairly new programmer and am having trouble with some UITextfields, basically i have two text fields and i want to limit the amount of characters in one of them to a certain amount, whilst allowing the other field to have lots.
I found a post that recommended this:
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
NSUInteger newLength = [[textField text] length] + [string length] - range.length;
return (newLength > 2) ? NO : YES;
}
However that seems to affect both text fields. I'm not sure how to target one field.
Can anyone help, also one thing, i get whats going on in that code up until - range. length, is the range the total amount of characters?
Ok so the issue here is that the object which contains this code is the delegate to both textfields. Two ways to solve it. Either dont add the textfield you dont care about the length of as a delegate or the better way would be to differentiate between the fields during the shouldChangeCharactersInRange method.
For the second part of your question- range is the character(s) that is/are being changed in the text field and consists of: The position of the string to change, the length of the string being changed.
My personal preference is to say if the text length is greater than max length and your not deleting then refuse the change.
-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
if(textField == self.textfieldYouWantToLimitTheLengthOf){
if(textField.text.length > 2 && ![string isEqualToString:#""]){
return NO;
}
}
return YES;
}

Knowing the complete changed string in textField:shouldChangeCharactersInRange:replacementString:

I just asked a question about how to monitor changes to a UITextField and received this response :
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)replacementStr {
// Enable "Next" if you like what's entered in the replacementStr
}
This works, but the replacement string is not the whole string, just what it is adding. How can I get the whole string? My objective is to see if the string in the text field is blank or equal to a certain number (in different scenarios).
Please note that the outlet to the text field doesn't work in this case, because this method is being called before the text in the field changes.
NSString * proposedNewString = [[textField text] stringByReplacingCharactersInRange:range withString:replacementString];
Swift Version
In Swift We need to cast textField's text to NSString. The following can be useful:
let newString = (textField.text! as NSString).replacingCharacters(in: range, with: string)
-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
NSString * searchStr = [textField.text stringByReplacingCharactersInRange:range withString:string];
// [textField2 setText:[textField1.text stringByReplacingCharactersInRange:range withString:string]];
NSLog(#"%#",searchStr);
return YES;
}

Limit text field length

Please tell me how I can set the range of a text field to a maximum of six and minimum of one.
Set self as textfield's delegate and implement this method:
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
NSString *newString = [textField.text stringByReplacingCharactersInRange:range withString:string];
if (newString.length < 1) {
// too short
} else if (newString.length > 6) {
// too long
}
return YES;
}
I'd suggest you to have a UILabel that will say in red text that text is too short or too long. Just preventing user from typing into textfield when they reach 6 chars or deleting last character when they change their mind is a very bad user experience.
Implement the delegate method textField:shouldReplaceCharactersInRange:replacementString: and have your implementation return NO if the resulting string would fall outside of your constraints.