UITextField - 在键入时输入第一个字符后添加一个字符

时间:2012-05-06 15:15:57

标签: iphone ios uitextfield uitextfielddelegate

我有一个包含高度值的UITextField。我想在用户输入UITextField时格式化字段的值。例如如果我想输入“5英尺10”的值,流程将为:

1. Enter 5
2. " ft " is appended immediately after I type 5 with leading & trailing space.

我的代码如下所示:

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

if ( [string isEqualToString:@""] ) return YES;

// currHeight Formatting
if ( textField == currHeight )  { 
   if (currHeight.text.length == 1) {   
        currHeight.text = [NSString stringWithFormat:@"%@ ft ", currHeight.text];    
        }
}
return YES; 
}

我被困在我输入的地步5没有任何反应。我必须点击任何按钮才能追加“ft”。

我可以不点击任何内容吗?

2 个答案:

答案 0 :(得分:6)

-shouldChangeCharactersInRange在更改文本字段之前被调用,因此长度仍为0(请参阅Using `textField:shouldChangeCharactersInRange:`, how do I get the text including the current typed character?)。试试这个:

- (BOOL)textField:(UITextField*)textField shouldChangeCharactersInRange:(NSRange)range
replacementString: (NSString*) string {
    if (textField == currHeight) {
        NSString *text = [textField.text stringByReplacingCharactersInRange:range
        withString: string];
        if (text.length == 1) { //or probably better, check if int
            textField.text = [NSString stringWithFormat: @"%@ ft ", text];
            return NO;
        }
    }
    return YES;
}  

答案 1 :(得分:1)

调用此函数时,currHeight.text的长度仍然为0.返回YES后,文本仅更新为5.

如果currHeight.text.length为0,string.length为1且字符串的第一个字符为数字,则执行您要执行的操作的方法是测试。