我正在尝试以短样式的形式显示 UIDatePicker,这可以在文档中找到,但我不太确定如何,我使用“hh:mm”手动完成,但是没有 Am 或 Pm 标签所以我尝试这样做
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = shortstyle
但是它说 unresolved 是一个无法识别的标识符。有人可以告诉我这里出了什么问题并解释如何修复它,我是 swift 的新手。
最佳答案
我过去曾使用此代码制作过一个能够告诉 AM 或 PM 的时钟。
首先,在 viewDidLoad 中添加:
myTimeLabel.text = ""
_ = NSTimer.scheduledTimerWithTimeInterval(1.0, target: self, selector: Selector("updateClock"), userInfo: nil, repeats: true)
然后在它自己的函数中:
func updateClock() {
let date = NSDate()
let calendar = NSCalendar.currentCalendar()
let components = calendar.components([.Hour, .Minute, .Second], fromDate: date)
//if statement if components hour > 12 then subtract 12 if not then leave it alone.
var hour = components.hour > 12 ? components.hour - 12 : components.hour
//this is an if statement if hour is = to 0 then 12 else it is equal to hour.
hour = hour == 0 ? 12 : hour
let hourString = hour > 9 ? "\(hour)" : "0\(hour)"
let minutes = components.minute > 9 ? "\(components.minute)" : "0\(components.minute)"
let seconds = components.second > 9 ? "\(components.second)" : "0\(components.second)"
//this is an if statement if am is > then am is pm if < than it is am.
let am = components.hour > 12 ? "PM" : "AM"
myTimeLabel.text = "\(hourString):\(minutes):\(seconds) \(am)"
}
我不是这段代码的起源。我从一个在线类(class)中得到了它,我花了一段时间,但无法找到该代码的第一个来源。
关于ios - 尝试在 UIDatePicker 中显示 Am 和 Pm,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34248632/