textFieldShouldBeginEditing在所有文本字段上触发

时间:2017-01-26 00:21:57

标签: ios swift

我想实现textFieldShouldBeginEditing,这样我就可以在弹出窗口中显示一些文本字段的对话框,其他文本字段将是自由文本。

我是这样实现的:

   func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool{


    if(textField == self.petType)
    {
        petTypePicker = CZPickerView(headerTitle: "Pet Types", cancelButtonTitle: "Cancel", confirmButtonTitle: "Choose")
        petTypePicker?.delegate = self
        petTypePicker?.dataSource = self
        petTypePicker?.needFooterView = true
        petTypePicker?.headerBackgroundColor = #colorLiteral(red: 0.4509803922, green: 0.3529411765, blue: 0.7647058824, alpha: 1)
        petTypePicker?.confirmButtonBackgroundColor = #colorLiteral(red: 0.4509803922, green: 0.3529411765, blue: 0.7647058824, alpha: 1)
        petTypePicker?.show()
        return false
    }
    else if(textField == self.petBread)
    {
        breedPicker = CZPickerView(headerTitle: "Breeds", cancelButtonTitle: "Cancel", confirmButtonTitle: "Choose")
        breedPicker?.headerBackgroundColor = #colorLiteral(red: 0.4509803922, green: 0.3529411765, blue: 0.7647058824, alpha: 1)
        breedPicker?.confirmButtonBackgroundColor = #colorLiteral(red: 0.4509803922, green: 0.3529411765, blue: 0.7647058824, alpha: 1)
        breedPicker?.delegate = self
        breedPicker?.dataSource = self
        breedPicker?.needFooterView = true
        breedPicker?.show()
        return false
    }
    else if(textField == self.petColor){
        colourPicker = CZPickerView(headerTitle: "Colours", cancelButtonTitle: "Cancel", confirmButtonTitle: "Choose")
        colourPicker?.headerBackgroundColor = #colorLiteral(red: 0.4509803922, green: 0.3529411765, blue: 0.7647058824, alpha: 1)
        colourPicker?.confirmButtonBackgroundColor = #colorLiteral(red: 0.4509803922, green: 0.3529411765, blue: 0.7647058824, alpha: 1)
        colourPicker?.delegate = self
        colourPicker?.dataSource = self
        colourPicker?.needFooterView = true
        colourPicker?.show()
        return false
    }
    else if(textField == self.petDateOfBirth){

        let currentDate = Date()

        DatePickerDialog().show(title: "DatePickerDialog", doneButtonTitle: "Done", cancelButtonTitle: "Cancel", minimumDate: nil, maximumDate: currentDate, datePickerMode: .date) { (date) in
            if let dt = date {
                let dateFormatter = DateFormatter()

                dateFormatter.dateStyle = .medium

                self.petDateOfBirth.text = "\(dateFormatter.string(from: dt) as String)"
            }
        }

        return false
    }
    else{


        return true

    }

}

但出于某种原因,这是发生的事情:

当返回为false时,它完美地工作,当return为true时,它会为所有texfield激发方法textFieldShouldBeginEditing,这使得它们都进入if语句,从而触发所有对话框。

任何想法为什么我遇到这种行为,请注意所有字段都在堆栈视图中

谢谢

1 个答案:

答案 0 :(得分:0)

我很高兴它有效;)。

使用实例属性isFirstResponder()来检查是否已经单击了正确的textField。在你的情况下,将你的if语句修改为if self.petType.isFirstResponder()就可以了。