将用户输入限制为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.
关于如何在swift中正确执行此操作的任何想法?
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.
推荐答案
这里是一个简单的例子:
Here is a simple example:
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屋!