如何以编程方式动态更新UILabel的文本

时间:2019-09-10 07:27:28

标签: swift uibutton uikit uilabel

我想使用一个简单的函数来更新UIlabel中的文本。我遇到了错误

  

线程1:致命错误:在隐式展开一个可选值时意外发现nil

我研究了这个问题,并发现了建议使用可选的绑定/保护语句的出色的post

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"

    }

}

1 个答案:

答案 0 :(得分:2)

问题似乎是您在loadView中手动添加了标签,但是您正在创建要添加到视图中的本地标签对象,而不是您的class属性,因此类属性nameLabel始终为nil

更改

let nameLabel = UILabel()

self.nameLabel = UILabel()