如何创建DatePicker扩展

时间:2019-03-10 18:53:43

标签: ios swift datepicker

我正在尝试将附加到文本字段的日期选择器代码移到扩展名中。我正在努力重构@objc代码。我不确定如何在doneButtonPressed代码中引用文本字段和日期选择器。

extension UIViewController {


    func datePicker(dateValue: UITextField) {

        let datePicker = UIDatePicker()

        datePicker.datePickerMode = .date

        let toolbar = UIToolbar()
        toolbar.sizeToFit()

        let doneButton = UIBarButtonItem(barButtonSystemItem: .done, target: nil, action: #selector(dateDonePressed))
        toolbar.setItems([doneButton], animated: false)

        dateValue.inputAccessoryView = toolbar

        dateValue.inputView = datePicker
    }

    @objc func dateDonePressed() {


        let dateFormatter = DateFormatter()
        dateFormatter.dateStyle = .medium
        dateFormatter.timeStyle = .none

        self.dateValue.text = dateFormatter.string(from: self.datePicker.date)
        self.view.endEditing(true)
    }
}

1 个答案:

答案 0 :(得分:1)

我只想在类中添加变量:

class ViewController {

    var textField: UITextField!
    var datePicker: UIDatePicker!

    override var viewDidLoad() {
        super.viewDidLoad() 
        ...// either set up textField here or in the extension
        datePicker.inputView = datePicker

}
extension ViewController {
    func datePicker(dateValue textField: UITextField){
        // if you decided to set the textfield in the extension, then:
        self.textField = textField
    }   
}

我不知道谁叫datePicker(dateValue,但是如果可以从那里访问文本字段,那么可能应该已经从其他地方设置和配置了文本字段。