如何在键入时在 NSString 中插入分组逗号?

发布于 2024-12-04 13:05:54 字数 2312 浏览 1 评论 0原文

用户在 UILabel 中输入数字字符串,文本将在用户键入时显示。

NSString *input = [[sender titleLabel] text];
[display_ setText:[[display_ text] stringByAppendingString:input]];

这工作正常,我使用 NSNumberFormatter 格式化显示,这样如果输入 1000000,则在点击另一个按钮时它会转换为 1,000,000。

但是,我希望在用户键入时显示这些分组逗号。我可以理解如何将内容插入字符串中,但我不清楚如何在用户输入时执行此操作。这需要一个可变字符串吗?

也许以某种方式监视字符串长度并将其分成三个组,然后制作并显示插入逗号的新字符串?我也许可以做到这一点,但正是“输入时”的部分让我陷入困境。

另一个想法是追加并显示该字符串,然后将显示内容读入一个新的 NSString 并对其进行格式化并立即再次显示。所以我尝试了一下,它几乎可以工作:

 if (userIsEntering)    
{
NSNumberFormatter *fmtr = [[NSNumberFormatter alloc] init];
[fmtr setNumberStyle:NSNumberFormatterDecimalStyle];
[fmtr setGroupingSeparator:@","];
[fmtr setDecimalSeparator:@"."];

NSString *out = [[display_ text] stringByAppendingString:digit];
NSNumber *num = [fmtr numberFromString:out];
NSString* formattedResult = [fmtr stringFromNumber:num];

[display_ setText: [NSString stringWithFormat:@"%@", formattedResult]];

[fmtr release];
}

而且,随着输入的每个数字创建和释放格式化程序,在 4 位数字之后它返回 null。

更新:我想出了如何在标签中做到这一点(在@Michael-Frederick 的帮助下)。它使用 NSNotification。

这对于非十进制数字非常有效,但是当我尝试输入小数点时,它会被忽略并删除。如果我不调用此方法,则接受小数点并且一切正常。

数字输入如下(通过按钮):

NSString *digit = [[sender titleLabel] text];
if (userIsStillWorking_)        
{
[display_ setText:[[display_ text] stringByAppendingString:digit]];
    }
else
{
[display_ setText: digit];
userIsStillWorking_ = YES;
    }
[[NSNotificationCenter defaultCenter] postNotificationName:@"updateDisplay" object:nil];

通知调用的 updateDisplay 方法是:

{
NSString *unformattedValue = [display_.text stringByReplacingOccurrencesOfString:
          @"," withString:@""];
unformattedValue = [unformattedValue stringByReplacingOccurrencesOfString:
          @"." withString:@""];
NSDecimalNumber *amount = [NSDecimalNumber decimalNumberWithString:unformattedValue];
NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
[formatter setGroupingSeparator:@","];
[formatter setDecimalSeparator:@"."];
[display_ setText: [ formatter stringFromNumber:amount]];
[formatter release];
}

我已尝试注释掉,

unformattedValue = [unformattedValue stringByReplacingOccurrencesOfString:
                   @"." withString:@""];

但这没有什么区别。

A user enters a numerical string in a UILabel and the text is displayed as the user types.

NSString *input = [[sender titleLabel] text];
[display_ setText:[[display_ text] stringByAppendingString:input]];

This works fine and I format the display using NSNumberFormatter so that if 1000000 is entered it is converted to 1,000,000 upon tapping another button.

However, I'd like to get those grouping commas to be displayed as the user types. I can understand how to insert things into strings, but how to do it as the user types is not clear to me. Would this require a mutable string?

Maybe somehow monitor the string length and split it into groups of three and make and display a new string with the commas inserted? I could probably do that, but it is the "as it is typed" part that has me stymied.

Another thought is to append and display the string, then read the display into a new NSString and format it and display it again right away. So I tried that, and it almost works:

 if (userIsEntering)    
{
NSNumberFormatter *fmtr = [[NSNumberFormatter alloc] init];
[fmtr setNumberStyle:NSNumberFormatterDecimalStyle];
[fmtr setGroupingSeparator:@","];
[fmtr setDecimalSeparator:@"."];

NSString *out = [[display_ text] stringByAppendingString:digit];
NSNumber *num = [fmtr numberFromString:out];
NSString* formattedResult = [fmtr stringFromNumber:num];

[display_ setText: [NSString stringWithFormat:@"%@", formattedResult]];

[fmtr release];
}

And, along with the fact that the formatter is created and released with every digit entered, after 4 digits it returns null.

UPDATE: I figured out how to do it in a label (with some help from @Michael-Frederick). It uses an NSNotification.

This works perfectly for non-decimal numbers, but when I try to enter a decimal point it is ignored and removed. If I do not invoke this method, the decimal point is accepted and all works well.

Numeric entry is as follows (from a button):

NSString *digit = [[sender titleLabel] text];
if (userIsStillWorking_)        
{
[display_ setText:[[display_ text] stringByAppendingString:digit]];
    }
else
{
[display_ setText: digit];
userIsStillWorking_ = YES;
    }
[[NSNotificationCenter defaultCenter] postNotificationName:@"updateDisplay" object:nil];

And the updateDisplay method called by the notification is:

{
NSString *unformattedValue = [display_.text stringByReplacingOccurrencesOfString:
          @"," withString:@""];
unformattedValue = [unformattedValue stringByReplacingOccurrencesOfString:
          @"." withString:@""];
NSDecimalNumber *amount = [NSDecimalNumber decimalNumberWithString:unformattedValue];
NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
[formatter setGroupingSeparator:@","];
[formatter setDecimalSeparator:@"."];
[display_ setText: [ formatter stringFromNumber:amount]];
[formatter release];
}

I've tried commenting out

unformattedValue = [unformattedValue stringByReplacingOccurrencesOfString:
                   @"." withString:@""];

but that makes no difference.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

沉睡月亮 2024-12-11 13:05:54

编辑:
用户无法在 uilabel 中键入内容。您需要使用 uitextfield 或 uitextview。

如果您想使用 uitextfield,请执行以下操作...

- (void) viewDidLoad {
[super viewDidLoad];
[textField addTarget:self action:@selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
}

- (void) textFieldDidChange:(UITextField *)textField {
    NSString *unformattedValue = [textField.text stringByReplacingOccurrencesOfString:@"," withString:@""];
    unformattedValue = [unformattedValue stringByReplacingOccurrencesOfString:@"." withString:@""];

    NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
    [formatter setNumberStyle:NSNumberFormatterDecimalStyle];
    [formatter setGroupingSeparator:@","];
    [formatter setDecimalSeparator:@"."];

    NSNumber *amount = [NSNumber numberWithInteger:[unformattedValue intValue]];
    textField.text = [formatter stringFromNumber:amount];

    [formatter release];
}

请注意,您应该在 textFieldDidChange 方法之外声明 NSNumberFormatter ,这是正确的。请注意,此代码实际上适用于整数。如果需要,您可能必须将 intValue 切换为 floatValue。该代码未经测试,它更多的是一般指南。

EDIT:
A user cannot type into a uilabel. You need to use either a uitextfield or a uitextview.

If you want to use a uitextfield, do something like this...

- (void) viewDidLoad {
[super viewDidLoad];
[textField addTarget:self action:@selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
}

- (void) textFieldDidChange:(UITextField *)textField {
    NSString *unformattedValue = [textField.text stringByReplacingOccurrencesOfString:@"," withString:@""];
    unformattedValue = [unformattedValue stringByReplacingOccurrencesOfString:@"." withString:@""];

    NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
    [formatter setNumberStyle:NSNumberFormatterDecimalStyle];
    [formatter setGroupingSeparator:@","];
    [formatter setDecimalSeparator:@"."];

    NSNumber *amount = [NSNumber numberWithInteger:[unformattedValue intValue]];
    textField.text = [formatter stringFromNumber:amount];

    [formatter release];
}

Note that you are correct that NSNumberFormatter should be declared outside of the textFieldDidChange method. Note that this code would actually be for an integer. You could have to switch intValue to floatValue if need be. This code is untested, it is more of a general guide.

音盲 2024-12-11 13:05:54

最好的方法是使用 2 个 UIlabel。 1 个标签用于通过使用 [NSString stringByAppendingString:digit] 来提供 NSNumberFormatter 对象;实际上显示了另一个标签。技巧是将未格式化的标签设置为隐藏,并将另一个标签设置为数字格式化程序的输出。通过将隐藏标签提供给数字格式化程序,并从数字格式化程序输出显示的标签,数字格式化程序应设置为 NSDecimalNumber 样式。这样设置完之后,显示的结果就是打字时自动出现的逗号。

The best way to do this is to use 2 UIlabels. 1 of the labels is used to feed your NSNumberFormatter object by using [NSString stringByAppendingString:digit]; The other label is actually displayed. The trick is to set the label that is unformatted to hidden and the other label is set as an output for the number formatter. By feeding the hidden label to the number formatter, and outputting the displayed label from the number formatter, the number formatter should be set to the NSDecimalNumber style. Setting it all up this way, the result displayed is automatic commas while typing.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文