如何获取 datePicker Swift 的初始值
我想获得时刻的初始价值,当我只是在滚动时间时,价值会改变。请观看照片,更清楚地了解我想要什么。
https://i.sstatic.net/hj5ga.jpg
@IBAction func datePickerChanged(_ sender: Any) {
let dateFormatter = DateFormatter()
dateFormatter.timeStyle = .short
dateFormatter.dateFormat = "HH:mm"
let strDate = dateFormatter.string(from: datePicker.date)
datePickerLb.text = strDate
}
I want to get initial value of timePicker, value changes when I am just scrolling time. Please watch photos it will be more clear to understand what I want.
https://i.sstatic.net/hj5GA.jpg
@IBAction func datePickerChanged(_ sender: Any) {
let dateFormatter = DateFormatter()
dateFormatter.timeStyle = .short
dateFormatter.dateFormat = "HH:mm"
let strDate = dateFormatter.string(from: datePicker.date)
datePickerLb.text = strDate
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您所需要做的就是更新
viewDidLoad
方法中的标签。我会将日期格式化程序声明移出该方法,以避免每次值更改时创建一个新的声明。请注意,您应该使用timeStyle
或dateFormat
,但不能同时使用两者。向最终用户显示日期时,您应始终遵守设备区域设置和设置,因此在这种情况下应选择timeStyle
:All you need is to update the label inside your
viewDidLoad
method. I would move the date formatter declaration out of that method to avoid creating a new one every time the value changes. Note that you should usetimeStyle
ordateFormat
but not both. When displaying dates to the end user you should always respect the devices locale and settings so you should choosetimeStyle
in this case:@Leo的回答很实用。需要补充的一件事是,如果您希望在选择器滚动时更新日期,那么不幸的是,
UIDatePicker
本身是不可能的。这是因为UIDatePicker
不是UIPickerView
的子类,它在内部管理 UIPickerView。这里的解决方案可能是使用自定义的 UIPickerView。然后对于 UIPickerView,您可以像这样实现它的委托方法:func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) ->细绳? {
}
}
currentTime
var 应该有一个didSet
来在更改时更新某些视图元素。The answer by @Leo is practical. One thing to add is that if you wanted the date updated while picker it is rolling then, unfortunately, it is impossible with
UIDatePicker
itself. This is becauseUIDatePicker
is not a subclass ofUIPickerView
and it manages a UIPickerView internally. The the solution here might be use a customUIPickerView
. Then for that UIPickerView you can implement it's delegate method like this:func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
}
}
currentTime
var should, for example, have adidSet
to update some view elements when it changes.