swift - 尽管 ShouldChangeCharactersIn 函数,文本字段仍允许所有字符

标签 swift text uitextfield character

当我试图内化我多年来使用的代码(没有太多理解)时,我创建了我的版本,理论上应该复制其用途。 我有一个文本字段,其中只允许使用小数和一个句点 - “.”。然而,目前,我的文本字段允许输入任何字符。

我已经导入了 UITextFieldDelegate 类,将我的 UITextField 连接为 socket ,并将我的文本字段设置为 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
}

此功能不会禁用多个句点和十进制数的反转。

最佳答案

我似乎为我工作,我将一些角色设置移动到一些惰性变量中,这样它只完成一次,而不是每次调用委托(delegate)时都完成。

import UIKit

class ContainerController: UIViewController, UITextFieldDelegate {


    @IBOutlet weak var textField: UITextField!

    //characterSet that holds digits
    lazy var allowed:CharacterSet = {
        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)
        return allowed
    }()

    lazy var inverted:CharacterSet = {
        return allowed.inverted
    }()

    override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) {
        super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        textField.delegate = self
    }


    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {

        print("shouldChangeCharactersIn", range)
        print("replacementString", string)
        //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
        } else if (textField.text?.contains("."))! && string.contains(".") {
            //if the text already contains a period and the string contains one as well, do not change output
            return false
        } else {
             //however, if not in the inverted set, allow the string to replace latest value in the text
            return true
        }
    }

}

关于swift - 尽管 ShouldChangeCharactersIn 函数,文本字段仍允许所有字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54580279/

相关文章:

CSS动画文本到图像

ios - 在 didEndEditing 中更改 UITextField 边框样式

ios - 无法将 View 和图像定位在场景底部

iOS/Swift/CoreBluetooth Ble 通知不工作

swift - :texture yields empty result 中的 SKTexture

html - 我需要在网页上居中 3 <div>

python - 将变量与其他文本一起放在 Canvas 上

ios - 在 alertview 文本字段中快速获取 nil 值

iphone - 在 View 弹出之前存储 UITextField 内容

swift - 合并具有相同属性但不同 ID 的 NSManagedObject,与 iCloud 同步导致重复(核心数据,Swift 1.2)