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

标签 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 ”。

我可以在不点击任何东西的情况下执行此操作吗?

最佳答案

-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;
}  

关于iphone - UITextField - 在输入第一个字符后添加一个字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10471648/

相关文章:

iPhone UITextField : how to insert new line by the return key?

iphone - 在 iPhone 中显示的输入框的 css 样式

iphone - 想要在 iOS 中设置文档(.doc)的字体

iphone - 如何使用Cocos2D制作没有瓦片 map 的滚动游戏?

iphone - 没有已知的选择器'JSONValue'实例方法

ios - UIStepper 吞下触摸

ios - 队列中的所有操作完成后立即释放 NSOperationQueue

iOS APNS - 缺少推送通知

ios - NativeScript 将 UIViewController 传递给 native iOS 方法

ios - 如何在 UILabel 中显示 UITextField 的文本?