Adam Xia
Adam Xia

Reputation: 73

How to change the width of a UILabel dynamically?

So I want to change the length of a UILabel(a progress bar) every time a button is pushed

Below is how I set up the Label in the view controller

@IBOutlet weak var progressLabel: UILabel!

@IBAction func answerPressed(_ sender: AnyObject) {
  progressBar.frame.size.width = progressBar.frame.size.width + 100
}

but I keep on getting the same value for progressBar.frame.size.width, is there a unique function for setting the width?

The yellow bar Does not increase in width after clicking the answerPressed

Upvotes: 0

Views: 287

Answers (3)

Adarsh KC
Adarsh KC

Reputation: 447

set constraint for the label it will automatically fit the text if the text count increases.

Upvotes: 3

Alan S
Alan S

Reputation: 594

There is a difference based on how you've added your view. I've added an example that has a UILabel added by code without constraints, and a UILabel added from the storyboard with constraints, I also gave this UILabel a width constraint and outletted that too:

class ViewController: UIViewController {


    var progressBar: UILabel!

    @IBOutlet weak var progressBarOutlet: UILabel! //From Storyboard
    @IBOutlet weak var progressBarBottomConstraint: NSLayoutConstraint! //Bottom constraint of the progressBarOutlet

    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        progressBar = UILabel(frame: CGRect(x: 0, y: 200, width: 10, height: 40))
        progressBar.backgroundColor = .systemPink
        view.addSubview(progressBar)

        let b = UIButton(frame: CGRect(x: 200, y: 500, width: 60, height: 60))
        b.setTitle("Add", for: .normal)
        b.setTitleColor(.blue, for: .normal)
        view.addSubview(b)
        b.addTarget(self, action: #selector(addWidth), for: .touchUpInside)
    }

    @objc func addWidth() {
        progressBar.frame.size.width = progressBar.frame.size.width + 50
        progressBarBottomConstraint.constant = progressBarBottomConstraint.constant + 50
        view.layoutIfNeeded()
    }
}

Upvotes: 0

If you just add this after changing the width :

progressBar.layoutIfNeeded()

It should works

Upvotes: 1

Related Questions