【发布时间】:2016-01-21 15:13:18
【问题描述】:
我正在制作一个指示 self.timer 值的 UILabel。
这是代码。 问题是我无法在 label.text 中指明 timeFormatter.stringFromDate(date_SSS)。
其实我还有一个 scrollView 和一个 pageControl 来水平滚动标签。但主要问题在于 UILabel 和 self.timer。
import UIKit
class ViewController: UIViewController {
private var label: UILabel!
private var timer: NSTimer!
let intArray: String = ["12:00:00", "12:50:00", "15:30:00", "16:40:00"]
let i = 0
override func viewDidLoad() {
let timeFormatter = NSDateFormatter()
timeFormatter.dateFormat = "HH:mm:ss"
self.timer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: "update:", userInfo: nil, repeats: true)
self.timer.fire()
for (var i = 0; i < intArray.count; i++) {
let label: UILabel = UILabel(frame: CGRectMake(CGFloat(index) * 50,100,150,200)
label.cornerRadius = 20
label.text = timeFormatter.stringFromDate(date_SSS)
view.addSubView(label)
}
}
func dateFromString(date:String) -> NSDate? {
let calendar = NSCalendar(calendarIdentifier: NSCalendarIdentifierGregorian)!
calendar.locale = NSLocale(localeIdentifier: "en_US_POSIX")
calendar.timeZone = NSTimeZone(abbreviation: "JST")!
let begin = date.startIndex
guard let hour = Int(date.substringWithRange(begin..<begin.advancedBy(2))),
let minute = Int(date.substringWithRange(begin.advancedBy(3)..<begin.advancedBy(5))),
let second = Int(date.substringWithRange(begin.advancedBy(6)..<begin.advancedBy(8))) else{
return nil
}
return calendar.dateBySettingHour(hour, minute: minute, second: second, ofDate: NSDate(), options: [])
}
func update(timer: NSTimer) {
let timeFormatter: NSDateFormatter = NSDateFormatter()
timeFormatter.timeZone = NSTimeZone(name: "GMT")
timeFormatter.dateFormat = "HH:mm:ss"
let time = dateFromString(intArray[i])
let remain = time!.timeIntervalSinceDate(NSDate())
let date_SSS = NSDate(timeIntervalSince1970: remain)
}
}
【问题讨论】:
-
这还能构建吗?我可以看到很多错误。例如
let intArray: String = ["12:00:00", "12:50:00", "15:30:00", "16:40:00"]将不起作用,因为您正在尝试创建String而不是[String]类型的数组。在viewDidLoad()中,当您声明label时,您缺少最后一个括号。我也很确定 UILabel 没有cornerRadius属性。