在iOS中以特定格式在文本字段中输入文本值

时间:2014-05-14 08:54:18

标签: ios objective-c

我正在开发iPhone应用程序。我需要在文本字段中以xx-xxx-xxx等修复格式从用户那里获取输入。所以我不知道怎么做?请建议我解决方案。

1 个答案:

答案 0 :(得分:0)

-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{


if (range.location == 10)    //this is calculate the overall string
 {
        return NO;
    }

    if ([string length] == 0)   //string length is `0` hide the keyboard
    {
        return YES;
    }

    if ((range.location == 2) || (range.location == 6) )    //apply the `-` between the overall string
    {
        NSString *str  = [NSString stringWithFormat:@"%@-",textField.text];
        textField.text = str;
    }

}