检查坐标有效性 - UITextField - iOS
Check co-ordinates validity - UITextField - iOS
我有一个 iOS 应用程序,其中有两个 UITextFields
允许用户手动输入纬度和经度坐标。我很困惑的一件事是,我怎样才能确保输入的数据是一个有效的坐标?
- 坐标只能是数字
- 坐标可以有负号。
- 坐标中不能有空格。
您说我还应该做其他检查吗?
我如何检查 UITextField.text
是否有字母和数字?我可以使用正则表达式吗?
更新
为了澄清我的问题,这些是我要检查的字符串类型:
- -2.42353463466(有效)
- 32.131ertf22(无效 - 它包含字符)
- 1.23141 4124(无效 - 包含空格)
您可以使用 Regex 来验证数字,但更简单的方法可能是尝试使用 NSNumberFormatter
将每个文本字段的字符串值转换为 double
并查看它是否工作:
NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];
numberFormatter.numberStyle = NSNumberFormatterDecimalStyle;
NSNumber *number = [numberFormatter numberFromString:myTextField.text];
if (number != nil) {
// The number is correct!
double coordinate = number.doubleValue;
NSLog(@"Coordinate: %f", coordinate);
} else {
// The number is incorrect!
NSLog(@"Invalid coordinate entered.");
}
一旦你得到每个坐标部分的两个 double
,你就可以使用 CLLocationCoordinate2DMake
函数形成一个 CLLocationCoordinate2D
。
形成你的CLLocationCoordinate2D
后,你可以使用CLLocationCoordinate2DIsValid
函数来检查纬度和经度部分是否在正确的范围内。
您可以检查特定的 CLLocationCoordinate2D 是否有效
CLLocationCoordinate2D myCoordinate=CLLocationCoordinate2DMake(latitude, longitude);
if (CLLocationCoordinate2DIsValid(myCoordinate)) {
NSLog(@"Coordinate valid");
} else {
NSLog(@"Coordinate invalid");
}
我有一个 iOS 应用程序,其中有两个 UITextFields
允许用户手动输入纬度和经度坐标。我很困惑的一件事是,我怎样才能确保输入的数据是一个有效的坐标?
- 坐标只能是数字
- 坐标可以有负号。
- 坐标中不能有空格。
您说我还应该做其他检查吗?
我如何检查 UITextField.text
是否有字母和数字?我可以使用正则表达式吗?
更新
为了澄清我的问题,这些是我要检查的字符串类型:
- -2.42353463466(有效)
- 32.131ertf22(无效 - 它包含字符)
- 1.23141 4124(无效 - 包含空格)
您可以使用 Regex 来验证数字,但更简单的方法可能是尝试使用 NSNumberFormatter
将每个文本字段的字符串值转换为 double
并查看它是否工作:
NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];
numberFormatter.numberStyle = NSNumberFormatterDecimalStyle;
NSNumber *number = [numberFormatter numberFromString:myTextField.text];
if (number != nil) {
// The number is correct!
double coordinate = number.doubleValue;
NSLog(@"Coordinate: %f", coordinate);
} else {
// The number is incorrect!
NSLog(@"Invalid coordinate entered.");
}
一旦你得到每个坐标部分的两个 double
,你就可以使用 CLLocationCoordinate2DMake
函数形成一个 CLLocationCoordinate2D
。
形成你的CLLocationCoordinate2D
后,你可以使用CLLocationCoordinate2DIsValid
函数来检查纬度和经度部分是否在正确的范围内。
您可以检查特定的 CLLocationCoordinate2D 是否有效
CLLocationCoordinate2D myCoordinate=CLLocationCoordinate2DMake(latitude, longitude);
if (CLLocationCoordinate2DIsValid(myCoordinate)) {
NSLog(@"Coordinate valid");
} else {
NSLog(@"Coordinate invalid");
}