Furqi
Furqi

Reputation: 2403

How to replace string in textfield iphone?

I am working on barcode app.So when user enter barcode in textfield so when it match (-)insert in that string like this let suppose textfield.text =12345786 so when it match it converted into 1234-5786 it is inserted but not deleting from my textfield.text value when my text is 123457869 or 1234578 dash(-)is not removing and textfield.text becomes 1234----. here is my code tell me where i am doing wrong? NSMutableString *a = [NSMutableString stringWithString:textfield.text];

if([textfield.text floatValue]>=8 ){ 


    [a insertString: @"-" atIndex: 4];
    //textfield.text = [textfield.text stringByReplacingOccurrencesOfString:@"-" withString:@""];

    textfield.text = a;
    NSLog(@"in if");

}
  else if([textfield.text length]<8){


    //[a insertString: @"" atIndex: 4];
    textfield.text = [textfield.text stringByReplacingOccurrencesOfString:@"-" withString:@""];

    NSLog(@"in else");
    //NSRange range = {4,5};
    //[a deleteCharactersInRange:range];
    //textfield .text = a;
}

Upvotes: 0

Views: 196

Answers (1)

Saad Ur Rehman
Saad Ur Rehman

Reputation: 798

NSString *abc=@"12345678";
    NSString * a =[abc substringWithRange:NSMakeRange(0, 4)];
    NSString *b =[abc substringWithRange:NSMakeRange(0, 8)];
    abc =[NSString stringWithFormat:@"%@-%@",a,b];
    NSLog(@"%@",abc);

Upvotes: 1

Related Questions