Trying to set only time in UIDatePicker in Swift 2

2020-02-07 04:12发布

问题:

I am trying to set the UIDatePicker to come up with the time only. The DatePicker comes up through an action when the textfield is pressed. I have not used the DatePicker Viewer. Any help is appreciated. Thanks

let starttimedatePicker = UIDatePicker()
    startTimeDiveTextField.inputView = starttimedatePicker
    starttimedatePicker.addTarget(self, action: "startTimeDiveChanged:", forControlEvents: .ValueChanged)


func startTimeDiveChanged(sender: UIDatePicker) {
    let formatter = NSDateFormatter()
    formatter.timeStyle = .ShortStyle
    startTimeDiveTextField.text = formatter.stringFromDate(sender.date)
}

回答1:

Try setting its Mode:

starttimedatePicker.datePickerMode = UIDatePickerMode.Time


回答2:

This may help you.

let starttimedatePicker = UIDatePicker()
starttimedatePicker.datePickerMode = UIDatePickerMode.Time
startTimeDiveTextField.inputView = starttimedatePicker
starttimedatePicker.addTarget(self, action: #selector(ViewController.startTimeDiveChanged), forControlEvents: .ValueChanged)


func startTimeDiveChanged(sender: UIDatePicker) {
    let formatter = NSDateFormatter()
    formatter.timeStyle = .ShortStyle
    startTimeDiveTextField.text = formatter.stringFromDate(sender.date)
}

If you are using DatePicker in Storyboard or Xib then set like this.