Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In iOS - How do I fit a UILabel to its text, without changing its position?

I'm calling sizeToFit on a UILabel which has right aligned text in it. It shrinks the height and width of the UILabeland fits the text to the top left of the UILabel.

Now...the position of the UILabel is incorrect. How can I make the UILabel stay in its original position (right aligned) or move it so it'll appear at its original position?

Once again - the problem is that the sizeToFit method is shrinking the width from the right side of the UILabel. It is treating the UILabel text as left aligned. But my text is right aligned. So, the right side border of the UILabel is where my text begins.

like image 217
Doron Avatar asked Apr 05 '11 08:04

Doron


People also ask

How do I change the dynamic 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 change my UILabel?

Change Font And Size Of UILabel In Storyboard To change the font or the size of a UILabel in a Storyboard or . XIB file, open it in the interface builder. Select the label and then open up the Attribute Inspector (CMD + Option + 5). Select the button on the font box and then you can change your text size or font.

What is UILabel in swift?

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


2 Answers

@implementation UILabel (Additions)

- (void)sizeToFitWithAlignmentRight {
    CGRect beforeFrame = self.frame;
    [self sizeToFit];
    CGRect afterFrame = self.frame;
    self.frame = CGRectMake(beforeFrame.origin.x + beforeFrame.size.width - afterFrame.size.width, self.frame.origin.y, self.frame.size.width, self.frame.size.height);
}

@end
like image 85
shiami Avatar answered Sep 28 '22 23:09

shiami


You check the widths before & after, then move the center of the view right by the difference / 2.

By the way, I think the "box" (frame) is shrunk in both directions, keeping the center intact.

like image 42
Steven Kramer Avatar answered Sep 29 '22 01:09

Steven Kramer