具有自定义UITextField选项的UIPickerView

时间:2018-08-29 13:19:44

标签: ios swift xcode uitextfield uipickerview

不确定这是否是菜鸟问题,因为这是我第一次使用UIPickerView。

我在班级中的UIPickerView具有以下数组:

let cameraBodies = ["A","B","C","D","E","F","G","H","I","J",
                    "K","L","M","N","O","P","Q","R","S","T",
                    "U","V","W","X","Y","Z","Other"]

当用户单击我的textField时,他们可以选择上述字符串。如果用户选择“其他”,我希望UIPickerView退出并更改为普通的TextField,以便用户可以输入自己的字符串。然后,如果用户删除了textField中的所有自定义文本,它将返回到UIPickerView。

我考虑过要根据用户选择显示/隐藏两个文本字段,但是我觉得这不是解决此问题的正确方法。

任何有关如何实现这一目标的帮助都会很棒。

这是我课程的一部分,与UIPickerView有关:

class newCameraController : UIViewController{

    var selectedBody: String?

    var cameraBodyCustomTextField: UITextField = {
        let textField = UITextField()
        textField.placeholder = "Custom Camera Body"
        return textField

    }()

    override func viewDidLoad() {
        super.viewDidLoad()

        createBodyPicker()
        createToolBar()
    }

    func createBodyPicker() {

        let bodyPicker = UIPickerView()
        bodyPicker.delegate = self
        cameraBodyTextField.inputView = bodyPicker
    }

    func createToolBar() {

        let toolBar = UIToolbar()
        toolBar.sizeToFit()

        let doneButton = UIBarButtonItem(title: "Done", style: .plain, target: self, action: #selector(newCameraController.dismissKeyboard))

        toolBar.setItems([doneButton], animated: false)
        toolBar.isUserInteractionEnabled = true
        cameraBodyTextField.inputAccessoryView = toolBar
    }

    override func dismissKeyboard() {
        view.endEditing(true)
    }

extension newCameraController: UIPickerViewDelegate, UIPickerViewDataSource {

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

    func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
        return cameraBodies.count
    }

    func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
        return cameraBodies[row]
    }

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

        selectedBody = cameraBodies[row]
        cameraBodyTextField.text = selectedBody
    }

    func pickerView(_ pickerView: UIPickerView, viewForRow row: Int, forComponent component: Int, reusing view: UIView?) -> UIView {

        var label: UILabel

        if let view = view as? UILabel {
            label = view
        } else {
            label = UILabel()
        }

        label.textColor = UIColor(red:0.63, green:0.63, blue:0.63, alpha:1.0)
        label.textAlignment = .center
        label.font = UIFont(name: "Avenir-Medium", size: 16.0)

        label.text = cameraBodies[row]

        return label
    }
}

1 个答案:

答案 0 :(得分:1)

根据我的意见,解决方案是: 在您的代码中,您将显示选择器代替键盘,这是正确的。 现在,当用户选择“其他”时,只需在cameraBodyTextField中显示所选值“其他”。 并在cameraBodyTextField下方显示一个额外的文本字段。 可以通过自动布局较高的约束和更流畅的动画来管理“显示/隐藏”。