Objective c 如何从UI文本字段获取数字?
我正在创建一个应用程序,用户将在两个Objective c 如何从UI文本字段获取数字?,objective-c,xcode,Objective C,Xcode,我正在创建一个应用程序,用户将在两个文本字段中输入车速,按下按钮,应用程序将告诉您哪辆车更快。我知道,要执行此操作,您需要使用NSNumberFormatter,但我是否将代码放在一个单独的方法中,该方法比较号码,并在单击按钮时调用该号码?尝试: NSDecimal *scannerValue = [NSDecimalNumber zero]; [[NSScanner scannerWithString:[textFieldInstance stringValue]] scanDecimal:s
文本字段中输入车速
,按下按钮
,应用程序将告诉您哪辆车更快。我知道,要执行此操作,您需要使用NSNumberFormatter
,但我是否将代码放在一个单独的方法中,该方法比较号码,并在单击按钮时调用该号码?尝试:
NSDecimal *scannerValue = [NSDecimalNumber zero];
[[NSScanner scannerWithString:[textFieldInstance stringValue]] scanDecimal:scannerValue];
if ([scannerValue decimalValue] != [NSDecimalNumber zero]) { // got a number
} else { // not a number
}
可用的方法通过指向类层次结构的链接进行记录。如果您需要更多帮助,请留下评论。在下面的按钮操作方法中尝试这样做:-
-(IBAction)calculateSpeed:(id)sender
{
NSDecimalNumber *first=[NSDecimalNumber decimalNumberWithString:self.txt.text];
NSDecimalNumber *second=[NSDecimalNumber decimalNumberWithString:self.txt2.text];
(second > first) ? NSLog(@"Mclaren is faster") : NSLog(@"BMW is faster");
}
首先,您应该将
UITextField
s限制为仅限十进制值。请参阅相同的
然后您可以执行以下操作:
-(IBAction)fasterCar:(id)sender {
int result = [self.txtField1.text intValue]; - [self.txtField1.text intValue];
if (result > 0)
NSLog(@"1st one is faster");
else if (result < 0)
NSLog(@"2nd one is faster);
else
NSLog(@"Both cars have equal speed");
}
-(iAction)快速卡:(id)发送方{
int结果=[self.txtField1.text intValue];-[self.txtField1.text intValue];
如果(结果>0)
NSLog(@“第一个更快”);
否则如果(结果<0)
NSLog(@“第二个更快);
其他的
NSLog(“两辆车的速度相同”);
}
可能看起来很老派,效果很好。Hmm,使用此方法,而不是使用
NSCharacterSet
验证文本是否为数字,然后使用floatValue
?是否将UITextField
限制为只有整数值?我喜欢老派方法,但仍有一个错误.我已将标签声明为-(IBAction)carSpeed1:(id)发件人;-(IBAction)carSpeed2:(id)sender;我是否也需要为这些操作编写参数?您指定的这两个操作根本不是标签…它们是iAction。但是您不需要将标签连接到iAction以便文本更改吗?