gpt4 book ai didi

ios - 消除数字中的多个小数点(快速)

转载 作者:行者123 更新时间:2023-12-01 15:48:43 26 4
gpt4 key购买 nike

我想将用户输入限制为仅有效数字并使用以下内容:

func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
guard CharacterSet(charactersIn: " -0123456789.,\t\n").isSuperset(of: CharacterSet(charactersIn: text)) else {
return false
}
return true
}

但这并不妨碍输入多于一位的小数点,例如“1.2.3”。有没有一种简单的方法可以防止这种情况发生?

最佳答案

尝试使用这个例子

guard CharacterSet(charactersIn: " -0123456789.,\t\n").isSuperset(of: CharacterSet(charactersIn: text)) else {
return false
}

var newText = (textView.text as NSString).replacingCharacters(in: range, with: text)
newText = newText.replacingOccurrences(of: ",", with: ".")

let strings = newText.split { character -> Bool in
return character == "\t" || character == "\n"
}

let numbers: [Double] = strings.compactMap { Double($0) }

return strings.count == numbers.count

关于ios - 消除数字中的多个小数点(快速),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63815501/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com