为什么我的约束不起作用? iOS版

时间:2015-01-03 14:25:50

标签: ios nslayoutconstraint

我只想在imgView上设置宽度和高度约束。我有以下代码:

UIImageView *imgView = [[UIImageView alloc] init];
imgView.center = self.view.center;
imgView.image = [UIImage imageNamed:@"favorites5-highlighted.png"];
imgView.contentMode = UIViewContentModeCenter;
[self.view addSubview:imgView];

// width constraint
[self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:[imgView(==100)]" options:0 metrics:nil views:NSDictionaryOfVariableBindings(imgView)]];

// height constraint
[self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:[imgView(==100)]" options:0 metrics:nil views:NSDictionaryOfVariableBindings(imgView)]];

我最终得到此错误:无法同时满足约束。 我抬起头来尝试添加:

imgView.translatesAutoresizingMaskIntoConstraints = NO;

self.view.translatesAutoresizingMaskIntoConstraints = NO;

编辑:

我只是想将imageView的宽度和高度设置为所需的属性。我第一次尝试使用

CGRect rect = CGRectMake(0, 0, 10, 10);
imgView.frame = rect;

但没有改变

1 个答案:

答案 0 :(得分:8)

两个问题:

  1. 您确实需要:

    imgView.translatesAutoresizingMaskIntoConstraints = NO;
    

    你不想要:

    self.view.translatesAutoresizingMaskIntoConstraints = NO;
    
  2. 您尝试设置center是徒劳的,因为当应用约束时,这将会丢失。不幸的是,您没有定义约束来定义图像视图的位置。您可以使用下面块的最后两行来执行此操作:

    UIImageView *imgView = [[UIImageView alloc] init];
    //imgView.center = self.view.center;                                // this does nothing in auto layout
    imgView.image = [UIImage imageNamed:@"favorites5-highlighted.png"];
    imgView.contentMode = UIViewContentModeCenter;
    imgView.translatesAutoresizingMaskIntoConstraints = NO;             // add this line
    [self.view addSubview:imgView];
    
    NSDictionary *views = NSDictionaryOfVariableBindings(imgView);
    
    // width constraint
    
    [self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:[imgView(100)]" options:0 metrics:nil views:views]];
    
    // height constraint
    
    [self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:[imgView(100)]" options:0 metrics:nil views:views]];
    
    // center align
    
    [self.view addConstraint:[NSLayoutConstraint constraintWithItem:self.view attribute:NSLayoutAttributeCenterX relatedBy:NSLayoutRelationEqual toItem:imgView attribute:NSLayoutAttributeCenterX multiplier:1.0 constant:0]];
    [self.view addConstraint:[NSLayoutConstraint constraintWithItem:self.view attribute:NSLayoutAttributeCenterY relatedBy:NSLayoutRelationEqual toItem:imgView attribute:NSLayoutAttributeCenterY multiplier:1.0 constant:0]];