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:
User clicks Button, Label displays new text, but frame.height is unchanged.
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.
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.
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 .
Open the Filters & Labels view (you will find it under Upcoming). Scroll to the bottom of your label list and tap Manage labels.
A view that displays one or more lines of informational text.
Call these methods immediately after changing the text
label.setNeedsLayout()
label.layoutIfNeeded()
this will give you the correct frame.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With