使用Swift,我有一个UILabel,它是在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
效果很好。
然后我尝试更改覆盖函数viewDidAppear
中的文本。我收到生成失败消息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"
}
}
试试这个:
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"
}
}
您的问题是middleDate是用viewDidLoad函数中的本地作用域声明的。为了使它成为类变量,您需要在类级别声明它。我稍微简化了这个类,只是为了让它能快速工作。