【问题标题】:How to change the order on how numbers are entered into a UITextField or UILabel如何更改数字输入到 UITextField 或 UILabel 的顺序
【发布时间】:2014-07-29 12:12:44
【问题描述】:

如何在UILabelUITextField 中输入数字,使它们在输入时始终向右而不是向左流动?换句话说,如果我输入一、二、你,我希望它们显示为 321 而不是传统的 123。

有没有简单的方法可以做到这一点?

非常感谢

【问题讨论】:

  • 你需要写case语句吗?
  • 我真的不知道有时会否决投票。 @Whoever 否决了这个问题 - 你能解释一下为什么投反对票,所以我知道为什么吗?

标签: ios objective-c nsstring uitextfield uilabel


【解决方案1】:

是的,有。从UITextFieldDelegate 协议实现一个方法将允许您这样做。

textField:shouldChangeCharactersInRange:replacementString:

询问 如果指定的文本应该更改,则委托。

讨论:每当用户输入一个 文本字段中的新字符或删除现有字符。

对于打字,您需要以下内容:

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

    NSMutableString *str = [NSMutableString stringWithString:[textField text]];
    if ( [string length] > 0 ) {
        // insert new characters at the beginning
        [str insertString:string atIndex:0];
    }
    else {
        // i'm leaving the implementation of the deletion code to you

    }

    [textField setText:str];

}

不要忘记将 UITextField 的委托设置为实现此功能的类。

请注意,此实现只是一个示例,如果用户粘贴超过 1 个字符的字符串,它将失败(在示例中,您必须反转字符串,然后将其插入到可变字符串的开头) .

【讨论】:

  • 酷,这应该可以,我会试一试并告诉你(会回来接受答案)。非常感谢
  • 我忘记了返回值,正如 Lapinou 所说。
【解决方案2】:

首先感谢 Alexander 提供的示例代码!

但是,这应该不能正常工作。您必须像这样返回 YES 或 NO:

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

    NSMutableString *str = [NSMutableString stringWithString:[textField text]];
    if ( [string length] > 0 ) {

        // insert new characters at the beginning
        [str insertString:string atIndex:0];
        [textField setText:str];

        return NO;
    }
    else {
        // i'm leaving the implementation of the deletion code to you
    }
    return YES;
}

【讨论】:

  • 非常感谢 Lapinou,您的代码运行良好,感谢您了解 Alexander 错过的内容,否则我无法弄清楚,我很感激。我将 Alexander 标记为答案,因为他是第一个,实际上他提供了 90% 的代码。非常感谢。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-01-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-30
相关资源
最近更新 更多