我有一个UITextField
:其文本为经度(双精度)值。我的设备用双点打印此双精度字符,例如24.000000
(而不是24,00000
)。
就是说,文本字段不应该接受无效值:为此,我使用decimalPad
键盘,该键盘包含数字和一个十进制符号(在我的情况下,该符号为,
,不是.
,但是看起来这会因地区而异。
当用户编辑文本字段时,双精度值将传递到MapKit
映射,因此在传递该值之前,该值必须有效。
纬度值的有效性非常清楚(value>-90
和value<90
,但是我不知道如何将字符串转换为有效的double。
<< [First首先,我的原始数据来自:
mapView.convert(touchPoint, toCoordinateFrom: mapView)
此返回带点的坐标,并在文本字段中显示该坐标。:如果用户正在编辑文本字段,则可以删除点,但不能再插入点。它的圆点应替换为逗号,因为在小数点内我只有一个逗号。Second
第三
:我尝试了此扩展名:extension String {
struct NumFormatter {
static let instance = NumberFormatter()
}
var doubleValue: Double? {
return NumFormatter.instance.number(from: self)?.doubleValue
}
}
测试文本字段中的值是否为双精度值。如果插入逗号,它将认为该值是双精度值。如果插入点,则值为零。如何验证我的经度值?
编辑完成后,didFinishEditing委托方法可以确保数字不以小数点结尾,因此输出为“ 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 == "." }
let integerPart = String(text[text.startIndex..<(text.index(of: ".") ?? text.endIndex)]) // makes sure the entered text is only digits or "." otherwise removes the non digit characters
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"
}