如何以编程方式动态更新 UILabel 的文本
how do I dynamically updated a UILabel's text programmatically
我想使用一个简单的函数来更新 UIlabel 中的文本。我收到错误
Thread 1: Fatal error: Unexpectedly found nil while implicitly unwrapping an Optional value
我调查了这个问题,发现这个非常好的 建议使用可选的 binding/guard 语句。
import UIKit
class ViewController: UIViewController {
var mainImageView: UIImageView!
var chooseButton: UIButton!
var nameLabel: UILabel!
override func loadView() {
view = UIView()
view.backgroundColor = .white
let btn = UIButton(type: .custom) as UIButton
btn.backgroundColor = .blue
btn.layer.borderColor = UIColor.darkGray.cgColor
btn.layer.borderWidth = 2
btn.setTitle("Pick a side", for: .normal)
btn.frame = CGRect(x: 100, y: 100, width: 200, height: 100)
btn.addTarget(self, action: #selector(clickMe), for: .touchUpInside)
btn.layer.cornerRadius = btn.frame.size.height/2
self.view.addSubview(btn)
let nameLabel = UILabel()
nameLabel.text = "Here is your side"
nameLabel.textAlignment = .center
nameLabel.backgroundColor = .cyan
nameLabel.frame = CGRect(x: 100, y: 400, width: 200, height: 100)
self.view.addSubview(nameLabel)
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
@objc func clickMe(sender:UIButton!) {
print("Button Clicked")
self.nameLabel.text = "updated title"
}
}
问题似乎是您在 loadView 中手动添加标签,但您创建的是添加到视图的本地标签对象,而不是您的 class 属性,因此 class 属性 nameLabel
始终为零
改变
let nameLabel = UILabel()
到
self.nameLabel = UILabel()
我想使用一个简单的函数来更新 UIlabel 中的文本。我收到错误
Thread 1: Fatal error: Unexpectedly found nil while implicitly unwrapping an Optional value
我调查了这个问题,发现这个非常好的
import UIKit
class ViewController: UIViewController {
var mainImageView: UIImageView!
var chooseButton: UIButton!
var nameLabel: UILabel!
override func loadView() {
view = UIView()
view.backgroundColor = .white
let btn = UIButton(type: .custom) as UIButton
btn.backgroundColor = .blue
btn.layer.borderColor = UIColor.darkGray.cgColor
btn.layer.borderWidth = 2
btn.setTitle("Pick a side", for: .normal)
btn.frame = CGRect(x: 100, y: 100, width: 200, height: 100)
btn.addTarget(self, action: #selector(clickMe), for: .touchUpInside)
btn.layer.cornerRadius = btn.frame.size.height/2
self.view.addSubview(btn)
let nameLabel = UILabel()
nameLabel.text = "Here is your side"
nameLabel.textAlignment = .center
nameLabel.backgroundColor = .cyan
nameLabel.frame = CGRect(x: 100, y: 400, width: 200, height: 100)
self.view.addSubview(nameLabel)
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
@objc func clickMe(sender:UIButton!) {
print("Button Clicked")
self.nameLabel.text = "updated title"
}
}
问题似乎是您在 loadView 中手动添加标签,但您创建的是添加到视图的本地标签对象,而不是您的 class 属性,因此 class 属性 nameLabel
始终为零
改变
let nameLabel = UILabel()
到
self.nameLabel = UILabel()