【发布时间】:2019-02-07 18:49:59
【问题描述】:
当我试图内化我多年来一直在使用的代码(没有太多理解)时,我创建了我的版本,理论上应该复制它的目的。 我有一个文本字段,其中我只允许十进制数字和一个句点 - “。”。但是,目前,我的 textField 允许输入任何字符。
我已导入 UITextFieldDelegate 类,将我的 UITextField 连接为插座,并将我的文本字段设置为 viewDidLoad 中的 textFieldDelefate。
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
//characterSet that holds digits
var allowed = CharacterSet.decimalDigits
//initialize the period for use as a characterSet
let period = CharacterSet.init(charactersIn: ".")
//adding these two characterSets together
allowed.formUnion(period)
//all the characters not in the allowed union
let inverted = allowed.inverted
//if latest input is from the characters not allowed is present (aka, empty), do not change the characters in the text range
if string.rangeOfCharacter(from: inverted) != nil
{
return false
}
//if the text already contains a period and the string contains one as well, do not change output
else if (textField.text?.contains("."))! && string.contains(".")
{
return false
}
//however, if not in the inverted set, allow the string to replace latest value in the text
else
{
return true
}
此功能不会禁用多个句点和十进制数的反转。
【问题讨论】:
-
你确定它不工作,我测试它时似乎工作。
-
没办法。只有小数和句点?
-
是的,只有数字和一个句点。您是否尝试在一个只有视图控制器和单个文本字段的简单项目中对其进行测试?
-
拍摄。听起来很愚蠢(如果不是太麻烦的话),您介意发布您的代码吗?我无法弄清楚我缺少什么。
-
到您的最后一条评论,是的。正是我一直在测试的地方,但没有运气。
标签: swift text uitextfield character