Search code examples
iosswiftuilabeluinavigationbar

Change label text in the navigation bar


I added a label to my NavigationBar with this code:

let navigationBar = self.navigationController?.navigationBar

let moneyFrame = CGRect(x: 330, y: 0, width: (navigationBar?.frame.width)!/2, height: (navigationBar?.frame.height)!)

let moneyLabel = UILabel(frame: moneyFrame)

moneyLabel.text = "\(money)"

navigationBar?.addSubview(moneyLabel)

The problem is: when I want to change the value of the variable "money", I always came with the solution to add another label. I just want to change the text of the label in the NavigationBar.


Solution

  • In the class scope define a label like this:

    var moneyLabel: UILabel?
    

    then in your function or wherever the code you posted sits in the class, do this:

    func myFunctionThatSetupNavigationLabel() {
        let navigationBar = self.navigationController?.navigationBar
    
        let moneyFrame = CGRect(x: 330, y: 0, width: 
        (navigationBar?.frame.width)!/2, height: (navigationBar?.frame.height)!)
    
        moneyLabel = UILabel(frame: moneyFrame)
    
        moneyLabel.text = "\(money)"
    
        navigationBar?.addSubview(moneyLabel)
    }
    

    Now just add this function to edit the title label:

    func updateTitle(title: String) {
        if let myTitleView = self.moneyLabel {
            myTitleView.text = title
        }
    }