I would like to use a simple function to update the text inside a UIlabel. I'm getting the error
Thread 1: Fatal error: Unexpectedly found nil while implicitly unwrapping an Optional value
I've looked into this problem and found this excellent post that suggested using optional binding/guard statements.
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"
}
}
The problem seems to be that you are adding the label manually in loadView but you are creating a local label object that you add to the view and not your class property so the class property nameLabel
is always nil
Change
let nameLabel = UILabel()
to
self.nameLabel = UILabel()