2011-11-04 16 views
0

我正在研究條形碼app.So當用戶在文本字段中輸入條形碼以便匹配時( - )插入該字符串,如下所示假設textfield.text = 12345786 因此當它匹配時將其轉換爲1234-5786 它插入但不是從我的textfield.text值刪除當我的文本是123457869或1234578破折號( - )不是刪除和textfield.text成爲1234 ----。 這裏是我的代碼告訴我我在哪裏做錯了? NSMutableString * a = [NSMutableString stringWithString:textfield.text];如何替換textfield iphone中的字符串?

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
NSString *[email protected]"12345678"; 
    NSString * a =[abc substringWithRange:NSMakeRange(0, 4)]; 
    NSString *b =[abc substringWithRange:NSMakeRange(0, 8)]; 
    abc =[NSString stringWithFormat:@"%@-%@",a,b]; 
    NSLog(@"%@",abc);