如何在swift 3.0中创建时间选择器视图?

时间:2016-09-18 05:45:00

标签: ios swift swift3

我在Swift中成功查看了datePicker UITextField。但我需要以HH:MM:SS的格式选择时间。我不知道。我需要及时应用选择的时间UITextField。所以,如何在Swift中制作Time Picker?请参考下图。 swift 2.2,2.0的答案也没关系。非常感谢朋友们!

enter image description here

3 个答案:

答案 0 :(得分:17)

针对Swift 3进行了更新:

如果要显示时间选择器,请使用下面的Swift 3的代码行:

变量声明:

let timePicker = UIDatePicker()

方法定义:

func openTimePicker()  {
    timePicker.datePickerMode = UIDatePickerMode.time
    timePicker.frame = CGRect(x: 0.0, y: (self.view.frame.height/2 + 60), width: self.view.frame.width, height: 150.0)
    timePicker.backgroundColor = UIColor.white
    self.view.addSubview(timePicker)
    timePicker.addTarget(self, action: #selector(yourViewControllerName.startTimeDiveChanged), for: UIControlEvents.valueChanged)
}

func startTimeDiveChanged(sender: UIDatePicker) {
    let formatter = DateFormatter()
    formatter.timeStyle = .short
    youtTextFieldName.text = formatter.string(from: sender.date)
    timePicker.removeFromSuperview() // if you want to remove time picker
}

答案 1 :(得分:9)

datePickerMode设置为time

Swift 3

self.datePicker.datePickerMode = .time

Swift 2.3或更低

self.datePicker.datePickerMode = .Time

注意:这样,您只需选择HoursMinutes,如果您想选择Seconds,您还需要选择自定义时间选择器

答案 2 :(得分:-1)

为 Swift 5+ 添加

用于计时器(它不显示秒部分。)

@IBOutlet weak var timerPicker: UIDatePicker!
...
 self.timerPicker.datePickerMode = .countDownTimer
 print("countdown duration",  String(timerPicker.countDownDuration))

enter image description here