I need to delete a character from an NSString when an NSRange is specified. I have a text field and I enter some text with number formatting and I get the value as $1,234,567.00.
Now i place my cursor after digit 5 and want to delete the number 5. In the Text delegate method shouldChangeCharactersInRange I get the range as (7,1) when I press backspace. I tried the following
modifiedFieldText = [modifiedFieldText stringByReplacingCharactersInRange:NSMakeRange(range.location - 1, range.length) withString:string];
But I am not able to delete the correct character. Any suggestion on this would be of great help. Please correct me where I went wrong.
I suspect that you must have some line of code that is modifying modifiedFieldText before you get to this line. You should make sure that the range is applied to the original textField contents, achieved by making the stringByReplacingCharactersInRange use the textfield directly, such as:
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
NSString *modifiedFieldText = [textField.text stringByReplacingCharactersInRange:range withString:string];
// now do whatever else you want
}
With that code, if the text field contained $1,234,567.00 and the user deleted the 5, the range would be {7, 1}, and the resulting modifiedFieldText would be $1,234,67.00, which you can presumably proceed and reformat to adjust the punctuation as you see fit.
If you are still having troubles, update your question with a more complete rendition of your shouldChangeCharactersInRange.
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 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.
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;
}
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;
}
In my iPad app. I have one UITextField. User would enter some value in that text field. This value has to be Alpha Numeric. I want to show an alert to the user if he/she enters any special character.
How can I do it? What should be the condition for alert?
Any help would be highly appreciated.
Thanks and regards,
PC
Implement textField:shouldChangeCharactersInRange:replacementString: in the delegate, check the replacement string for special characters, and disallow the replacement if you detect any.
The easiest way to check for non-alphanumerics is as follows:
if ([replacementString rangeOfCharacterFromSet:[[NSCharacterSet alphanumericCharacterSet] invertedSet]].location != NSNotFound) {
// There are non-alphanumeric characters in the replacement string
}
You can do it as :-
#define ACCEPTABLE_CHARECTERS #" ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
NSCharacterSet *acceptedInput = [NSCharacterSet characterSetWithCharactersInString:ACCEPTABLE_CHARECTERS];
if (![[string componentsSeparatedByCharactersInSet:acceptedInput] count] > 1)
return NO;
else
return YES;
}
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.