如何确保在文本字段中仅选择选择器数据

时间:2019-11-21 12:27:55

标签: ios swift uitextfield uipicker

我在UITextfield中的选择器函数中使用以下代码,如何确保从数组中选择值,并且没有其他数据输入 我分享了下面的代码,我使用“后卫”检查字段是否为空 代码

var spinneCPickerData: [String] = ["1", "2", "3", "4", "5"]
    @IBOutlet var pickerfield: UITextField!

override func viewDidLoad() {
        super.viewDidLoad()

        let spinnerCPicker = UIPickerView()
        spinnerCPicker.delegate = self
        pickerfield = spinnerCPicker

    }

 func numberOfComponents(in pickerView: UIPickerView) -> Int {
        return 1
    }

    func pickerView( _ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {

            return spinneCPickerData.count




        }

    func pickerView( _ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {

            return spinneCPickerData[row]


    }

    func pickerView( _ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {

            pickerfield.text = spinneCPickerData[row] as String

        view.endEditing(true)
    }
    func pickerView(pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
        // This method is triggered whenever the user makes a change to the picker selection.
        // The parameter named row and component represents what was selected.
    }


fun setdata(){

guard let text data = PostCategoryField.text, !postcategory.isEmpty,  else {
            self.view.makeToast("Please Enter the Category!")
            return }

}

1 个答案:

答案 0 :(得分:0)

您需要将inputView设置为pickerfield

像这样,您可以...

声明属性pickerView

 private let pickerView = UIPickerView(frame: .init(x: 0, y: 0, width: UIScreen.main.bounds.width, height: 216))

viewDidLoad中的方法设置委托和数据源。

    pickerView.dataSource = self
    pickerView.delegate = self
    pickerfield.inputView = pickerView

因此,当pickerfield成为第一响应者时,将显示选择器视图而不是键盘。

因此用户必须从选择器视图中选择一个值

更新

您可以通过if-let通过以下方式进行操作。您需要将此代码放在要验证textfield值的位置。

//When pickerfield.text value is one of the value of spinneCPickerData array
if let txt = pickerfield.text, spinneCPickerData.contains(txt) {

       print("the textfield'd value is from the array")
 }