【问题标题】:How do I call the self.timer's changing value and indicate it at the label.text the ViewDidLoad's如何调用 self.timer 更改值并在 label.text 中指示它 ViewDidLoad
【发布时间】: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 属性。

标签: ios swift swift2


【解决方案1】:

好吧,您没有在更新方法中设置标签,因此很难看出它会如何变化。也许我不明白你的问题。

【讨论】:

  • 感谢您回答我的问题。你正在接近的观点没有错。我尝试在 update() 函数中设置标签,但如果我这样设置就会出现问题。正如自拍中所说,标签也会按1秒制作,而且它的外观很脏。我该如何解决?
猜你喜欢
  • 2022-12-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-02-09
  • 1970-01-01
相关资源
最近更新 更多