swift - 验证经度 double 值

标签 swift uitextfield double mapkit

我有一个UITextField :其文本是经度( double )值。我的设备打印这个带有点的 double ,例如 24.000000 (而不是 24,00000 )。

也就是说,文本字段不应接受无效值:为此,我使用 decimalPad键盘,包含数字和小数点符号(在我的例子中,符号是 , ,而不是 . 但看起来这根据区域设置而有所不同)。

当用户编辑文本字段时, double 值将传递到 MapKit映射,因此在传递该值之前该值必须有效。

纬度值的有效性非常清楚( value>-90value<90 ),但我不知道如何将字符串转换为有效的 double 值。

首先,就我而言,初始数据来自:

mapView.convert(touchPoint, toCoordinateFrom: mapView)

此函数返回带点的坐标并在文本字段中显示该坐标。

第二:如果用户正在编辑文本字段,他可以删除一个点,但不能再插入它。它的点应该用逗号替换,因为在小数点中我只有一个逗号。

第三:我尝试了这个扩展:

extension String {
    struct NumFormatter {
        static let instance = NumberFormatter()
    }

    var doubleValue: Double? {
        return NumFormatter.instance.number(from: self)?.doubleValue
    }
}

测试文本字段中的值是否为 double 值。如果我插入逗号,它会将该值视为 double 。如果我插入一个点,则该值为 nil。

如何验证我的经度值?

最佳答案

我为自己编写了这个函数,以便在触发文本字段的 didBeginEditing 委托(delegate)方法时验证输入。此函数尝试从字符串生成有效的 Double 数字,否则将返回默认值。

编辑完成后,didFinishEditing委托(delegate)方法可以确保数字不以小数点字符结尾,以便输出“10”。将为“10”,但我自己以不同的方式处理这部分。

您需要根据自己的目的更改函数或小数点字符或小数位数。就我而言,每次更改文本字段中的值时,都会验证和操作文本,以确保用户在文本字段中输入时无法输入无效的输入。

private func validate(from text: String?) -> String {
    guard var text = text else { return "1.0" }  // makes sure the textfield.text is not nil
    guard text.first != "." else { return "0." } // prevents entering ".0"

    text = text.filter{ CharacterSet.decimalDigits.isSuperset(of: CharacterSet(charactersIn: $0.description)) || $0 == "." } // makes sure the entered text is only digits or "." otherwise removes the non digit characters
    let integerPart = String(text[text.startIndex..<(text.index(of: ".") ?? text.endIndex)]) // it is the digits before the first decimal point
    var decimalPlaces = "" // digits after the decimal point
    var afterIntegerText = "" // the text after the integer number before the decimal point
    if let decimalPointIndex = text.index(of: ".") { // if the number has a decimal point
        afterIntegerText = String(text[decimalPointIndex..<text.endIndex]) // "10.12345 will result become ".12345"
        decimalPlaces = String(afterIntegerText.replacingOccurrences(of: ".", with: "").prefix(2)) // ".12345" will become "12"
        decimalPlaces = afterIntegerText.isEmpty ? "" : ".\(decimalPlaces)" // generates the text of decimal place character and the numbers if any
    }
    return "\(integerPart + decimalPlaces)" // "10.*$1.2." will become "10.12"
}

关于swift - 验证经度 double 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48459854/

相关文章:

ios - UITableViewCell Segue 有时会连接到错误的 Controller

ios - AVCaptureDevice 设备为空

iOS - 在 ViewController 之间共享数据

iphone - 如何将焦点设置到 iPhone 中的下一个 uitextfield?

c# - 如何提高 double 类型对于大数的精度?

c# - 如何将 Number.Double Access 列值转换为 Decimal?

ios - Swift & Core Data - 将实体添加到现有实体

ios - 在一个 View Controller 中强制横向方向后重置 Xcode 中的自动旋转(swift 4)

ios - 用户界面文本域 : Text jumps up and down while typing

c++ - C++ 中的高斯积分不起作用。为什么?