Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/swift/17.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ios 按下按钮时显示一天中的时间_Ios_Swift_Swift3 - Fatal编程技术网

Ios 按下按钮时显示一天中的时间

Ios 按下按钮时显示一天中的时间,ios,swift,swift3,Ios,Swift,Swift3,我需要显示一天中的时间(例如,14:02),并将其显示在一个UILable中 以下是检索系统时间的代码: let date = Date() let calendar = Calendar.current let components = calendar.dateComponents([.hour, .minute, .second, .nanosecond], from: date) _ = components.hour 我不知道如何把它送到标签上 mylable.text = "??

我需要显示一天中的时间(例如,
14:02
),并将其显示在一个
UILable

以下是检索系统时间的代码:

let date = Date()
let calendar = Calendar.current
let components = calendar.dateComponents([.hour, .minute, .second, .nanosecond], from: date)
 _ = components.hour
我不知道如何把它送到标签上

mylable.text = "???"

谢谢。

您需要使用
DateFormatter
而不是
DateComponents
来获取特定格式的
Date
Time

let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "HH:mm"
let time = dateFormatter.string(from: Date())
mylable.text = time

@安东尼普拉托诺夫欢迎你,伙计:)还有一个小问题。我无法将其集成到按钮功能中,因为它只能在super.ViewDidLoad中工作。我试图在super.ViewDidLoad中创建一个布尔值并使用if语句。。。没有用…UPD:我把整个代码块放在按钮funs中,它成功了。谢谢again@AntonPlatonov用不起作用的代码编辑你的问题。UPD:我把整个代码块放在按钮func中,它就起作用了。再次感谢