NSLayoutConstraints code pour centre un point de vue et de maintenir son ratio d'aspect

J'aimerais que mon sous-vue d'être en 16:9 rectangle centré au-dessus de la superview. En d'autres termes, j'aimerais qu'il:

  1. être aussi large que c'est superview, mais pas plus large que 400px (INTERFACE utilisateur peut faire pivoter en mode paysage),
  2. être centré horizontalement lorsqu'il est plus étroit que c'est superview,
  3. ont c'est top épinglé à son superview du haut, et
  4. modifier la hauteur pour maintenir un aspect ratio 16:9.

Ce code ne fait presque ça, sauf que je vais avoir du mal à se faire horizontale contraintes de travailler et de ne pas être sur ou sous contrainte...

- (void)viewDidLoad
{
    [super viewDidLoad];
    //Do any additional setup after loading the view.

    UIView *contentView = [[UIView alloc] init];
    contentView.backgroundColor = [UIColor redColor];
    [self.view addSubview:contentView];

    contentView.translatesAutoresizingMaskIntoConstraints = NO;

    NSDictionary *views = NSDictionaryOfVariableBindings(contentView);
    NSMutableArray *constraints = [NSMutableArray array];

    //this layout string is more like 'wishful coding'.  I don't see why it wouldn't work
    //but clearly this one is the problem
    [constraints addObjectsFromArray:[NSLayoutConstraint
                                      constraintsWithVisualFormat:@"H:|-(>=0)-[contentView(<=400)-(>=0)-]"
                                      options:0 metrics:0 views:views]];

    //this centering constraint below almost does the job, but doesn't give me a way
    //to specify width, changing the one above to just @"H:[contentView(<=400)]"
    //doesn't work either
    [constraints addObject:
     [NSLayoutConstraint constraintWithItem:contentView
                                  attribute:NSLayoutAttributeCenterY
                                  relatedBy:NSLayoutRelationEqual
                                     toItem:self.view
                                  attribute:NSLayoutAttributeCenterY
                                 multiplier:1.f constant:0.f]];

    //9:16 works fine, I think
    [constraints addObject:
     [NSLayoutConstraint constraintWithItem:contentView
                                  attribute:NSLayoutAttributeHeight
                                  relatedBy:NSLayoutRelationEqual
                                     toItem:contentView attribute:NSLayoutAttributeWidth
                                 multiplier:9.0/16.0 constant:0.0]];

    //pin the tops works fine, I think
    [constraints addObjectsFromArray:
     [NSLayoutConstraint constraintsWithVisualFormat:@"V:|-0-[contentView]"
                                             options:0 metrics:0 views:views]];

    [self.view addConstraints:constraints];
}
InformationsquelleAutor danh | 2013-08-14