如何让GetTheTime函数返回值并显示到label.StringValue中
解决Swift函数返回时间字符串并显示到Label的问题
嘿,我来帮你搞定这个问题~首先你的原函数有个小问题:它是无返回值的(Void类型),内部定义的theTime变量没有被返回出来,而且还重复创建了Calendar实例,我们先调整函数让它能返回格式化后的时间字符串,再调用它赋值给Label。
第一步:修改原函数,让它返回时间字符串
我们把函数改成返回String类型,同时优化一下时间格式(给个位数的时/分/秒补零,显示更规范):
func getTheTime() -> String { let calendar = Calendar.current let date = Date() let hour = calendar.component(.hour, from: date) let minutes = calendar.component(.minute, from: date) let seconds = calendar.component(.second, from: date) // 用String(format:)格式化,补零保证两位数显示 let timeString = String(format: "%02d:%02d:%02d", hour, minutes, seconds) print(timeString) // 保留原有的打印逻辑 return timeString }
小提示:原函数里的
NSCalendar.current和Calendar.current是等价的,Swift里用Calendar.current更符合现代语法习惯哦。
第二步:调用函数并赋值给Label
假设你已经有一个Label实例(比如通过IBOutlet连接的,名字叫timeLabel),直接调用函数并赋值即可:
// 如果是macOS的NSTextField,用stringValue timeLabel.stringValue = getTheTime() // 如果是iOS的UILabel,记得用text属性(不是stringValue) // timeLabel.text = getTheTime()
这样就能把实时的时间字符串显示到Label上啦~
内容的提问来源于stack exchange,提问作者John Martin
相关产品推荐
相关产品推荐

