使用textViewDidChange

时间:2019-01-07 02:27:38

标签: ios swift uikit

我想将输入到UITextView中的内容限制为Doubles,每个Double由一个空格分隔。当然,这意味着只能使用一个小数点。

以下代码删除字母和符号,但不适用于小数。输入小数点后,键入的下一个字符将删除小数点。

我在做什么错??

import UIKit

class ViewController: UIViewController, UITextViewDelegate {

    @IBOutlet weak var dataInputField: UITextView!

    var currentEntryHasDecimalPoint:Bool = false
    var validChars: Set<Character> = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", ".", " "]


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


    func textViewDidChange(_ textView: UITextView ) {

        if let str = dataInputField.text, !str.isEmpty {

            let validChar:Bool = Set(str).isSubset(of: validChars)
            if validChar {

                let newChar = str.last!
                switch newChar {
                case ".":
                    currentEntryHasDecimalPoint = true
                    validChars.remove(".")
                case " ":
                    currentEntryHasDecimalPoint = false
                    validChars.insert(".")

                default:
                    print("default")
                }
            }

            else {
                dataInputField.deleteBackward()
            }
        }
    }

}

1 个答案:

答案 0 :(得分:1)

由于deleteBackward()确实更改了textView,因此也会触发textViewDidChange。当您输入"."后接一个字母时,validChars已从"."中删除,该字母将被删除并触发textViewDidChange,然后"."将被删除。被删除。您应该使用正则表达式/^(?:[0-9]+(?:\.$|\.[0-9]+)?(?:\s+|\s*$))+$/而不是Set操作来验证文本。

func textViewDidChange(_ textView: UITextView ) {

    if let str = textView.text,
        !str.isEmpty,
        let regex = try? NSRegularExpression(pattern: "^(?:[0-9]+(?:\\.$|\\.[0-9]+)?(?:\\s+|\\s*$))+$", options: []),
        regex.numberOfMatches(in: str, options: [], range: NSRange(location: 0, length: str.count)) == 0
    {
        textView.deleteBackward()
    }
}