在 Swift 中将用户输入限制为有效的十进制数 [英] Limiting user input to a valid decimal number in Swift
问题描述
我在 Objective-c 中找到了很多关于如何做到这一点的指南,但我希望看到一种更面向 Swift 的方式来做到这一点.
I have found a lot of guides on how to do this in objective-c, but I would like to see a more Swift-oriented way of doing this.
我有一个 UITextField,用户可以在其中输入货币价格.文本字段调用十进制键盘.然而,在 iPad 上,出现的键盘上有一整套非十进制符号.
I have a UITextField that a user enters a currency price into. The textfield calls a decimal pad keyboard. However, on the iPad, the keyboard that comes up has a whole range of non-decimal symbols.
基本上,对于每一次按键,我想让非数字或超出单个小数的任何内容都无法输入到该字段中.如果输入了小数,我想让输入第二个小数成为不可能.如果小数被删除,我想确保用户可以再次输入小数.
Basically, for every single key press, I would like to make it impossible for a non-number or anything beyond a single decimal to be typed into the field. If a decimal is typed, I would like to make it impossible to enter a second decimal. If the decimal is deleted, I'd like to make sure the user can enter a decimal again.
有关如何快速正确执行此操作的任何想法?
Any ideas on how to properly do this in swift?
我也看到了类似这里发布的解决方案:将 UITextField 限制为一位小数点 Swift但我不知道在哪里放置函数或如何调用它们.每当我尝试在参数中放入 NSRange 时,我都会收到一个错误,指出我没有正确创建范围.
I also see solutions like the ones posted here: Limit UITextField to one decimal point Swift But I have no idea where to place the functions or how I should call them. Whenever I try to put in NSRange in the parameters, I receive an error that I am not creating a range properly.
推荐答案
这是一个简单的例子:
import UIKit
class ViewController: UIViewController, UITextFieldDelegate {
@IBOutlet weak var textField: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
self.textField.delegate = self
}
//Textfield delegates
func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool { // return NO to not change text
switch string {
case "0","1","2","3","4","5","6","7","8","9":
return true
case ".":
let array = Array(textField.text)
var decimalCount = 0
for character in array {
if character == "." {
decimalCount++
}
}
if decimalCount == 1 {
return false
} else {
return true
}
default:
let array = Array(string)
if array.count == 0 {
return true
}
return false
}
}
}
这篇关于在 Swift 中将用户输入限制为有效的十进制数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!