itenyh
itenyh

Reputation: 1939

LayoutConstraint added but frame is not changed

Look at the code below:

- (void)viewDidLoad {
[super viewDidLoad];

UIView *view = [[UIView alloc] init];

view.translatesAutoresizingMaskIntoConstraints = NO;

NSLayoutConstraint *heightConstraint = [NSLayoutConstraint constraintWithItem:view attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationEqual toItem:nil attribute:NSLayoutAttributeHeight multiplier:1.0 constant:30];
[view addConstraint:heightConstraint];

NSLog(@"view : %@", view);

}

And the info printed out to be:

<UIView: 0x7ae4c1b0; frame = (0 0; 0 0); layer = <CALayer: 0x7ae4e790>>

The frame is not changed to be 30 as I set up with the constraint. Why? How to make it work?

Upvotes: 0

Views: 200

Answers (1)

rdelmar
rdelmar

Reputation: 104082

As I said in my comment, you need to add the view to a superview first, and call layoutIfNeeded on that superview. I don't know why you had trouble with NSLayoutAttributeNotAnAttribute, it works fine for me.

- (void)viewDidLoad {
    [super viewDidLoad];
    UIView *view = [[UIView alloc] init];
    view.translatesAutoresizingMaskIntoConstraints = NO;

    NSLayoutConstraint *heightConstraint = [NSLayoutConstraint constraintWithItem:view attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationEqual toItem:nil attribute:NSLayoutAttributeNotAnAttribute multiplier:1.0 constant:30];
    [view addConstraint:heightConstraint];
    [self.view addSubview:view];
    [self.view layoutIfNeeded];
    NSLog(@"view : %@", view);
}

When I run this, the log gives me this result,

2014-10-23 22:05:07.701 FrameTest[4293:1869985] view : <UIView: 0x7b724d40; frame = (0 0; 0 30); layer = <CALayer: 0x7b720760>>

Upvotes: 1

Related Questions