I have a UILabel right now and the UILabel.text value changes regularly.
The problem I am having is that if each time the UILabel.text value changes, the UILabel width changes according to the content of the label.
How can I fix this? This is my code I have right now:
outputLabel.text = errorMessage;
outputLabel.hidden = NO;
[outputLabel sizeToFit];
UPDATE The reason I am using sizeToFit is because I need the height to automatically change.
Thanks,
Peter
The steps are as follows: Create a subclass of UILabel which you will use anywhere you want your label text to be selectable. Add a long press gesture recogniser. Upon long press, present the UIMenuController shared instance with the menu items you need, in this case, Copy and Speak.
You can calculate the width of the string and see if the width is greater than label width. Save this answer.
sizeToFit()Resizes and moves the receiver view so it just encloses its subviews.
you can create a category or a subclass of UILabel and add this method to resize only the height of the label depending to the input text
- (void)heightToFit {
CGSize maxSize = CGSizeMake(self.frame.size.width, CGFLOAT_MAX);
CGSize textSize = [self.text sizeWithFont:self.font constrainedToSize:maxSize lineBreakMode:self.lineBreakMode];
CGRect labelRect = self.frame;
labelRect.size.height = textSize.height;
[self setFrame:labelRect];
}
and use it instead sizeToFit
Use [UILabel sizeThatFits:]
with a CGSize
with infinite height like (320, 10000)
.
I subclassed UILabel and overrode the sizeThatFits method to look like this:
- (CGSize)sizeThatFits:(CGSize)size
{
CGSize res = [super sizeThatFits:size];
return CGSizeMake(size.width, res.height);
}
Then if I add the label into a nib I place a UILabel from the object library. After that I make sure to set the class of the placed label to my custom class instead of the default of UILabel.
It basically just overrides the new width with the original width so it never changes width, but dynamically changes height.
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