Dmitry Borovsky
Dmitry Borovsky

Reputation: 558

sizeToFit and constraints

I have an view:

my view

There is layout constraint between label1 and label2. Pressing on button adds text from text view to label1. After it label 1 is resized to fit text (sizeToFit is called). And after resizing it looks like constraints don't work:

constraint

Does somebody has an idea how to make constraints work?

My coode:

@interface ViewController ()
{
    CGFloat _width;
}
@end

@implementation ViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
}

- (void) viewDidAppear:(BOOL)animated
{

    _width = self.l1.frame.size.width;
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
- (IBAction)addText:(id)sender {
    self.l1.text = [NSString stringWithFormat:@"%@ %@", self.l1.text, self.text.text];
    self.l1.frame = CGRectMake(self.l1.frame.origin.x, self.l1.frame.origin.y, _width, 0);
    [self.l1 sizeToFit];
}
@end

Upvotes: 3

Views: 3197

Answers (2)

masteroleary
masteroleary

Reputation: 1034

I had a similar issue in which an UIImageView was at the top of several UILabelViews. The constraints were set to keep a small distance between the top image and the stack of labels below.

The problem was that when loading an unknown image size into the UIImage the height would change, but the labels to follow did not push down, and were covered by the image.

I tried to delete the set height of the UIImageView but XCode would not let me.

I resolved the issue by reducing the priority on the explicit UIImageview height constraint to 1.

After, the labels moved down the ViewController with even space between the image and themselves, as expected.

Upvotes: 0

Dmitry Borovsky
Dmitry Borovsky

Reputation: 558

I've found the reason: height constraint was equal to 40 of label 1. When I change it to greater or equal , all other constraints work ok.

Upvotes: 4

Related Questions