来自xib的ios8加载视图:无法同时满足约束

时间:2014-10-22 12:04:28

标签: ios objective-c autolayout

我的设置非常简单:

我在UIView

中有空的VC和xib

MyView.m:

- (void) commonInit {
    [[[NSBundle mainBundle] loadNibNamed:@"MyView" owner:self options:nil] objectAtIndex:0];
    [self addSubview:self.view];
}

-(id)initWithCoder:(NSCoder *)aDecoder{
    self = [super initWithCoder:aDecoder];

    if (self) {
        [self commonInit];
    }

    return self;
}

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];

    if (self) {
        [self commonInit];
        self.bounds = self.view.bounds;
    }

    return self;
}

我的MyVC.m

- (void)viewDidLoad {
    [super viewDidLoad];
    self.myView = [[MyView alloc] init];
    NSDictionary *bindings = @{@"myView": self.myView};
    [self.view addSubview:self.offlinePromoView];

    self.myView.translatesAutoresizingMaskIntoConstraints = NO;

    [self.view addConstraint:[NSLayoutConstraint constraintWithItem:self.myView
                                                          attribute:NSLayoutAttributeCenterX
                                                          relatedBy:NSLayoutRelationEqual
                                                             toItem:self.view
                                                          attribute:NSLayoutAttributeCenterX multiplier:1.0 constant:0]];
    [self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|-(topSpacing)-[myView]-|" options:0 metrics:@{@"topSpacing": @70} views:bindings]];
    [self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|-[myView]-|" options:0 metrics:nil views:bindings]];
}

我希望我的子视图从顶部填充70个点,并且与控制器的视图具有相同的宽度。但我明白了:

(
    "<NSLayoutConstraint:0x176ae8d0 MyView:0x176a7770.centerX == UIView:0x176a7840.centerX>",
    "<NSLayoutConstraint:0x176b10b0 MyView:0x176a7770.leading == UIView:0x176a7840.leadingMargin>",
    "<NSLayoutConstraint:0x176b0900 UIView:0x176a7840.trailingMargin == MyView:0x176a7770.trailing>"
)
我的VC中

0x176a7840self.view

我做错了什么?

2 个答案:

答案 0 :(得分:0)

试试这样: -

[self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|[myView]-(-70)-|" options:0 metrics:nil views:bindings]];
[self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|[myView]|" options:0 metrics:nil views:bindings]];

答案 1 :(得分:0)

NSDictionary *bindings = NSDictionaryOfVariableBindings(view);
[self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|-(==70)-[view]-|" options:0 metrics:nil views:bindings]];
[self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|-[view]-|" options:0 metrics:nil views:bindings]];