lolinger 2001 lolinger 2001 - 1 year ago 147
Swift Question

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.

Answer Source

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
    }
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download