Trying to set only time in UIDatePicker in Swift 2

2020-02-07 04:42发布

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)
}

2条回答
虎瘦雄心在
2楼-- · 2020-02-07 04:51

Try setting its Mode:

starttimedatePicker.datePickerMode = UIDatePickerMode.Time
查看更多
聊天终结者
3楼-- · 2020-02-07 04:59

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.

enter image description here

查看更多
登录 后发表回答