textField允许所有字符,尽管ShouldChangeCharactersIn函数

时间:2019-02-07 18:50:00

标签: swift text uitextfield character

当我试图内部化多年来使用的代码(没有太多了解)时,我创建了自己的版本,理论上 应该复制其目的。 我有一个textField,其中只允许使用十进制数字和一个句点-“。”。但是,此刻,我的textField允许输入任何字符。

我已经导入了UITextFieldDelegate类,将我的UITextField连接为插座,并将我的文本字段设置为viewDidLoad中的textFieldDelefate。

{{1}}

此功能不会禁用一个以上的句点和十进制数字的倒数。

1 个答案:

答案 0 :(得分:0)

我似乎为我工作,我将一些字符设置移到了一些惰性变量中,这样就只能执行一次,而不是每次调用委托时都执行一次。

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
        }
    }

}