1

I need my user to enter numbers to type his telephone number.The user can only enter 8 numbers(for eg. XXXXXXXX). I need to change the phone number to be in the format XX-XX-XXXX.

This is what I have tried:

[tfDID.text insertString:@"-" atIndex:2];
[tfDID.text insertString:@"-" atIndex:5];

But it is returning me an error saying:

No Visible @interface for 'NSString' declares the selector 'insertString:atIndex:'

Need some guidance on this. Sorry if this is a stupid question.

lakshmen
  • 28,346
  • 66
  • 178
  • 276

4 Answers4

4

No Visible @interface for 'NSString' declares the selector 'insertString:atIndex:'

As you are trying to mutate the textbox's value, which returns you NSString.

NSString object can not be mutated, so convert it into a mutable string then manupulate it.

Make your string NSMutableString.

As,

NSMutableString *tfDIDString=[NSMutableString stringWithString:tfDID.text];
[tfDIDString insertString:@"-" atIndex:2];
[tfDIDString insertString:@"-" atIndex:5];
Anoop Vaidya
  • 46,283
  • 15
  • 111
  • 140
4

[UITextField text] is NSString, you need to declare local variable of NSMutableString and perform insertString operations on it

Hope it helps you

P.J
  • 6,547
  • 9
  • 44
  • 74
1

Implement <UITextFieldDelegate> and then do:

-(void)textFieldDidChange:(UITextField*)textField
{
    if( textField.text.length == 2 || textField.text.length == 5 ){
        textField.text = [textField.text stringByAppendingString:@"-"];
    }
}
Roland Keesom
  • 8,180
  • 5
  • 45
  • 52
1

Completely agree with the answer suggesting making it a mutable string. Just to play devils advocate you could do:

NSString *partOne = [NSString stringWithRange:NSMakeRange(0,2)];
NSString *partTwo = [NSString stringWithRange:NSMakeRange(2,2)];
NSString *partThree = [NSString stringWithRange:NSMakeRange(4,4)];

NSString *formattedNumber = [NSString stringWithFormat:@"%@-%@-%@",partOne,partTwo,partThree];

I've written it out longhand but you could compress the string declarations for the parts in to the stringWithFormat call if you don't mind nesting and sacrifcing a bit of readability.

Cocoadelica
  • 3,006
  • 27
  • 30