TestShroff TestShroff - 7 days ago 5
iOS Question

last character disappears in

I am implementing the following method to save data of text field in case of change to _detailsDictionary ,but when it saves ,the last letter enterd in textfield.text doesn't appear,e.g if I am saving "Krish",then only kris will be saved.How thids can be fixxed?

-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
NSInteger field = textField.tag;

if(field ==1)
{

if(textField.text ==[_detailsDictionary valueForKey:@"FName"])
{
NSLog(@"cell1.userDetailTextField.text %@",textField.text);
}
else
{
[_detailsDictionary setObject:textField.text forKey:@"FName"];
}
return YES;
}
if(field ==2)
{


if(textField.text ==[_detailsDictionary valueForKey:@"MName"])
{
NSLog(@"cell1.userDetailTextField.text %@",textField.text);
}
else
{
[_detailsDictionary setObject:textField.text forKey:@"MName"];
}

return YES;
}

if(field ==3)
{
if(textField.text ==[_detailsDictionary valueForKey:@"LName"])
{
NSLog(@"cell1.userDetailTextField.text %@",textField.text);
}
else
{
[_detailsDictionary setObject:textField.text forKey:@"LName"];
}
return YES;
}

if(field ==4)
{
if(textField.text ==[_detailsDictionary valueForKey:@"City"])
{
NSLog(@"cell1.userDetailTextField.text %@",textField.text);
}
else
{
[_detailsDictionary setObject:textField.text forKey:@"City"];
}
return YES;
}

if(field ==5)
{
if(textField.text ==[_detailsDictionary valueForKey:@"State"])
{
NSLog(@"cell1.userDetailTextField.text %@",textField.text);
}
else
{
[_detailsDictionary setObject:textField.text forKey:@"State"];
}
return YES;
}

if(field ==6)
{
if(textField.text ==[_detailsDictionary valueForKey:@"Country"])
{
NSLog(@"cell1.userDetailTextField.text %@",textField.text);
}
else
{
[_detailsDictionary setObject:textField.text forKey:@"Country"];
}
return YES;
}

if(field ==7)
{

if(textField.text ==[_detailsDictionary valueForKey:@"DOB"])
{
NSLog(@"cell1.userDetailTextField.text %@",textField.text);
}
else
{
[_detailsDictionary setObject:textField.text forKey:@"DOB"];
}
return YES;
}
return NO;
}

Answer

In shouldChangeCharactersInRange method you will not get the full text from textfield.text as this methods get called before text actually enters in textfield

You need to use

NSString *strText = [textField.text stringByReplacingCharactersInRange:range withString:string];

here in strText you will get fullText