Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iOS Swift Label Frame Height Not Updating Correctly

I have a Label whose text changes each time the user clicks a Button. However, the Label.frame.height value does not update immediately even though the Label content has changed. The function to change the Label is called in multiple places, yet the height ONLY updates just inside the @IBAction block, and its value lags one click cycle. My code is as follows:

func changeLabelText() {
//Here I have an algorithm (not shown) that generates myMutableString 
Label.attributedText = myMutableString  //Label is updated.
}


@IBAction func changeLabelButton(sender: UIButton) {
print("1. Height = ", Label.frame.height) //Height updates here, but it's the old value.  
changeLabelText()  //Label is updated.
print("2. Height = ", Label.frame.height) //Returns same height as Line 1!!
}


override func viewDidLoad() {
super.viewDidLoad()
print("3. Height = ", Label.frame.height) //Initially, height is 21.0 when ViewController first loads.
changeLabelText() //Label is updated.
print("4. Height = ", Label.frame.height) //Returns height = 21.0, even though simulator shows Label updated!!
}

In summary, this is what's happening:

  1. User clicks Button, Label displays new text, but frame.height is unchanged.

  2. User clicks Button again, Label text changes again, frame.height updates this time, but updates to the old value it should've had on Step 1.

I'm relatively new to Swift, and any help with this is appreciated.

like image 759
dimery2006 Avatar asked Feb 21 '16 21:02

dimery2006


People also ask

How do I change the height of a label in Swift?

To give a dynamic height to an UIlabel in swift we can use the frame property of UILabel. We can create a frame using the CGRect which allows us to give different variables like x position, y position, width, and height.

How do I expand a label in Swift?

All you have to do is initially set the UILabel to have a numberOfLines of lets say 7 and line break mode to be . byTruncatingTail . Then on button click simply change the numberOfLines to 0 and line break mode to be . byWordWrapping .

How do I change labels in Swift?

Open the Filters & Labels view (you will find it under Upcoming). Scroll to the bottom of your label list and tap Manage labels.

What is UILabel?

A view that displays one or more lines of informational text.


1 Answers

Call these methods immediately after changing the text

label.setNeedsLayout()
label.layoutIfNeeded()

this will give you the correct frame.

like image 188
paulvs Avatar answered Sep 16 '22 20:09

paulvs