如何仅设置几个月的UIDatePicker

时间:2019-04-13 15:59:59

标签: ios swift datepicker

是否可以在UIDatePicker列表中仅显示几个月?

@IBOutlet weak var monthsTextField: UITextField!
private var datePicker : UIDatePicker?

    override func viewDidLoad() {
        super.viewDidLoad()

        datePicker = UIDatePicker()
        datePicker?.datePickerMode = .date
        datePicker?.addTarget(self, action: #selector(HomePageViewController.dateChanged(datePicker: )), for: .valueChanged)

        let tapGesture = UITapGestureRecognizer(target: self, action: #selector(HomePageViewController.viewTapped(gestureRecognizer:)))

        view.addGestureRecognizer(tapGesture)

        monthsTextField.inputView = datePicker
}



@objc func dateChanged(datePicker: UIDatePicker) {

        let dateFormatter = DateFormatter()
        //dateFormatter.dateFormat = "MMMMMd"
        dateFormatter.setLocalizedDateFormatFromTemplate("MMMM")

        monthsTextField.text = dateFormatter.string(from: datePicker.date)
        //view.endEditing(true)

    }

点击屏幕底部的DatePicker后,显示带有月/日/年的列表

1 个答案:

答案 0 :(得分:0)

UIDatePicker不支持仅显示几个月的模式。这样的结果不会给您Date。您所知道的只是月份的名称或号码。

要执行所需的操作,您需要使用UIPickerView。设置选择器视图的数据源,以使用从以下位置获得的月份名称数组:

let monthNames = Calendar(identifier: .gregorian).monthSymbols