如何将函数返回到标签StringValue

时间:2018-05-02 22:05:54

标签: swift

func GetTheTime() {
    let calendar = NSCalendar.current
    let date = Date()
    _ = Calendar.current

    let hour = calendar.component(.hour, from: date)
    let minutes = calendar.component(.minute, from: date)
    let seconds = calendar.component(.second, from: date)
    print("\(hour):\(minutes):\(seconds)")
    var theTime = "\(hour):\(minutes):\(seconds)"

如何调用它并将其返回并显示为label.StringValue?

2 个答案:

答案 0 :(得分:0)

要返回内容,请添加箭头以及您要返回的数据类型。像这样:

func getTheTime() -> String {
    let calendar = NSCalendar.current
    let date = Date()
    _ = Calendar.current
    let hour = calendar.component(.hour, from: date)
    let minutes = calendar.component(.minute, from: date)
    let seconds = calendar.component(.second, from: date)
    return "\(hour):\(minutes):\(seconds)"
}

然后你可以像字符串一样使用getTheTime()函数,这样就可以了:

myLabel.text = getTheTime()

如果您希望它始终以秒为单位显示更新时间,则必须调用定时函数,您可以在此处找到堆栈溢出的答案。

答案 1 :(得分:0)

试试这个

 func getTheTime()-> String{

    let date = Date()
    let calendar = Calendar.current
    let hour = calendar.component(.hour, from: date)
    let minutes = calendar.component(.minute, from: date)
    let seconds = calendar.component(.second, from: date)
    let time =  "\(hour):\(minutes):\(seconds)"

    label.text = String(time) //label is the name of your label

或者你可以使用 DateFormatter