快速设置文本字段输入范围编号在 17 - 100 之间

问题描述

所以我制作了一个包含用户输入的一堆数据的表单,其中输入的是年龄,我希望用户只输入 17 - 100 之间的数据。

之后我有这个包含每个文本字段验证的函数,所以如果验证正确,它将使按钮启用

这是我的验证函数

func buttonReady() {
    
    if umurTextField.text != "" && domisiliTextField.text != "" && rencanaPembelianTextField.text != "" && luasTanahTextField.text != "" && luasBangunanTextField.text != "" && budgetTextField.text != "" && metodePembayaranTextField.text != "" && lantaiRumahTextField.text != "" {
        ButtonSearch.isEnabled = true
        ButtonSearch.backgroundColor = #colorLiteral(red: 0.5176470588,green: 0.3294117647,blue: 0.1333333333,alpha: 1)
        ButtonSearch.setTitleColor(#colorLiteral(red: 1.0,green: 1.0,blue: 1.0,alpha: 1.0),for: .normal)
        ButtonSearch.layer.cornerRadius = 25
    }else {
        ButtonSearch.isEnabled = false
        ButtonSearch.setTitleColor(#colorLiteral(red: 1,green: 1,blue: 1,alpha: 1),for: .normal)
        ButtonSearch.layer.cornerRadius = 25
        ButtonSearch.layer.backgroundColor = #colorLiteral(red: 0.6666666667,green: 0.4745098039,blue: 0.2588235294,alpha: 0.4408410685)
    }
}

到目前为止,我只是将验证设为非空,但我想将“umurTextField”验证设为仅在 17 - 100 之间,我该怎么做?

谢谢

解决方法

您可以使用

测试它是否在范围内
17...100 ~= Int(umurTextField.text) ?? .min

示例

for test in ["8","34","b","99","104"] {
    print("\(test): \(17...100 ~= Int(test) ?? .min)")
}

8:假
34:真的
b: 假
99:真的
104:假

,

可能

if let res = umurTextField.text,let value = Int(res),(17...100).contains(value),.......... {

}