I was just fiddling around with AutoLayout (using code), and bumped into something I don't really understand. I made a simple example to demonstrate the issue:

- (void)viewDidLoad
{
    [super viewDidLoad];

    //create views
    UIView *redView = [UIView new];
    redView.backgroundColor = [UIColor redColor];
    redView.translatesAutoresizingMaskIntoConstraints = NO;

    UIView *blueView = [UIView new];
    blueView.backgroundColor = [UIColor blueColor];
    blueView.translatesAutoresizingMaskIntoConstraints = NO;

    //add views to viewcontroller's view
    [self.view addSubview:redView];
    [self.view addSubview:blueView];

    //add contraints
    NSDictionary *views = NSDictionaryOfVariableBindings(redView, blueView);

    [self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|-[redView]-|" options:0 metrics:nil views:views]];
    [self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|-[blueView]-|" options:0 metrics:nil views:views]];

    [self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|-[redView]-[blueView]-|" options:0 metrics:nil views:views]];
}

I would expect the following outcome: http://i.stack.imgur.com/LCWQP.png

But instead it gives the following outcome: http://i.stack.imgur.com/DJK5i.png

Now, I know it can be solved by using [NSLayoutConstraint constraintWithItem: attribute: relatedBy: toItem: attribute: multiplier: constant: ], but I was wondering if there is is a VisualFormat option, or there is just something missing in my code ...

Thanks in advance for your help during my learning journey!

有帮助吗?

解决方案

@"V:|-[redView]-[blueView]-|"

This says that the bottom of redView should be aligned to the top of blueView, which it is. It says nothing about the relative heights of redView and blueView.

If you want them to be equal height, you can say so.

@"V:|-[redView]-[blueView(==redView)]-|"
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top