如何在textfield iphone中替换字符串?

时间:2011-11-04 06:33:26

标签: iphone insert uitextfield

我正在使用条码app.So当用户在文本字段中输入条形码时所以匹配时( - )插入该字符串就像这样 假设textfield.text = 12345786 所以当它匹配时它转换成1234-5786 当我的文本是123457869或1234578破折号( - )没有删除而textfield.text变为1234时,它被插入但不从我的textfield.text值中删除。 这是我的代码告诉我我在哪里做错了?     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;
}

1 个答案:

答案 0 :(得分:1)

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