防止用户在Objective-C中输入多个小数
我正在制作一个唯一的数字输入应用程序(仍然),其中用户按下按钮,我将一个值存储到字符串中以显示在标签中。
在大多数情况下,效果很好,除了我无法弄清楚如何阻止用户在单个字符串中输入多个小数。 。
我查看了这个堆栈溢出的问题,但是试图为自己的代码修改代码,只是导致了很多错误。有人有建议吗?
- (void)numberBtn:(UIButton *)sender {
if (self.sales.text.length < 10) {
if(self.sales.text.length != 0){
NSString *lastChar = [self.sales.text substringFromIndex:[self.sales.text length] - 1];
if([lastChar isEqualToString:@"."] && [sender.titleLabel.text isEqualToString:@"."] && [sender.titleLabel.text stringByAppendingString:@"."]){
return;
}
if ([lastChar isEqualToString:@""] && [sender.titleLabel.text isEqualToString:@""]){
self.numbers = @"0.";
}
if ([self.sales.text rangeOfString:@"."].length > 0) {
NSArray *array = [self.sales.text componentsSeparatedByString:@"."];
if (array.count == 2) {
NSString *decimal = array.lastObject;
if (decimal.length > 2) {
return;
}
}
}
}
self.numbers = [NSString stringWithFormat:@"%@%@",self.numbers,sender.titleLabel.text];
self.sales.text = self.numbers;
}
}
I am making an only number input app (still) in which users press a button, I store a value into a string to display in a label.
Works great for the most part, except I cannot figure out how to prevent users from entering more than one decimal in a single string. .
I looked at this Stack overflow question, but trying to amend the code for my own just resulted in a whole bunch of errors. Does anyone have any advice?
- (void)numberBtn:(UIButton *)sender {
if (self.sales.text.length < 10) {
if(self.sales.text.length != 0){
NSString *lastChar = [self.sales.text substringFromIndex:[self.sales.text length] - 1];
if([lastChar isEqualToString:@"."] && [sender.titleLabel.text isEqualToString:@"."] && [sender.titleLabel.text stringByAppendingString:@"."]){
return;
}
if ([lastChar isEqualToString:@""] && [sender.titleLabel.text isEqualToString:@""]){
self.numbers = @"0.";
}
if ([self.sales.text rangeOfString:@"."].length > 0) {
NSArray *array = [self.sales.text componentsSeparatedByString:@"."];
if (array.count == 2) {
NSString *decimal = array.lastObject;
if (decimal.length > 2) {
return;
}
}
}
}
self.numbers = [NSString stringWithFormat:@"%@%@",self.numbers,sender.titleLabel.text];
self.sales.text = self.numbers;
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
两个步骤...
。
。
,请返回。如果没有,请继续处理您的按钮输入:
Two steps...
.
.
If it does, return. If not, continue processing your button input: