如何使用Swift以编程方式引用UILabel强引用?

时间:2014-10-22 22:14:58

标签: swift ios8 uilabel strong-references

使用Swift,我有一个在viewDidLoad覆盖函数中以编程方式创建的UILabel:

var middleDate = UILabel(frame: CGRect(x: (screenWidth / 2) - 45, y: 0, width: 90, height: 20))
    middleDate.text = "3:13:46 PM"
    middleDate.font = UIFont(name: "ArialMT", size: 13)
    middleDate.textAlignment = .Center

哪个效果很好。

然后我试图更改覆盖函数viewDidAppear中的文本。 我收到Build Failed消息Use of unresolved identifier 'middleDate'

如果我使用界面构建器并在视图上拖放UILabel,那么给它一个强大的参考,它可以很好地工作。有没有办法引用具有强引用的编程创建对象?

或者我这样做不正确?


这就是我在ViewController.swift上的内容:

我觉得有一种更好,更清洁的方法可以做到这一点。

override func viewDidLoad() {

    super.viewDidLoad()

    var middleDate = UILabel(frame: CGRect(x: (screenWidth / 2) - 45, y: 0, width: 90, height: 20))
    middleDate.text = "3:13:46 PM"
    middleDate.font = UIFont(name: "ArialMT", size: 13)
    middleDate.textAlignment = .Center

    self.myTopView.addSubview(middleDate)
}

override func viewDidAppear(animated: Bool) {
    super.viewDidAppear(animated)

    var timer = NSTimer.scheduledTimerWithTimeInterval(1.0,
        target: self,
        selector: Selector("getLocalTime:"),
        userInfo: nil,
        repeats: true)

    let mainLoop = NSRunLoop.mainRunLoop()
    mainLoop.addTimer(timer, forMode: NSDefaultRunLoopMode)

    func getLocalTime(timer: NSTimer) { 

        var todaysDate:NSDate = NSDate()
        var dateFormatter:NSDateFormatter = NSDateFormatter()
        var centerDateFormatter:NSDateFormatter = NSDateFormatter()

        dateFormatter.dateFormat = "h:mm:ss"            

        var DateInFormat:String = dateFormatter.stringFromDate(todaysDate)            

        middleDate.text = "hello"


    }
}

1 个答案:

答案 0 :(得分:3)

试试这个:

class ViewController: UIViewController {

    var middleDate = UILabel(frame: CGRect(x: (360 / 2) - 45, y: 200, width: 90, height: 20))

    override func viewDidLoad() {

        super.viewDidLoad()

        middleDate.text = "3:13:46 PM"
        middleDate.font = UIFont(name: "ArialMT", size: 13)
        middleDate.textAlignment = .Center

        self.view.addSubview(middleDate)
    }

    override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated)

        middleDate.text = "hello"
    }
}

您的问题是在viewDidLoad函数中使用本地范围声明了middleDate。为了使它成为类变量,您需要在类级别声明它。我简化了课程,只是为了让它快速适合我。