将子视图的NSLayoutConstraints设置为父视图

时间:2013-06-17 19:50:12

标签: ios nslayoutconstraint

在UITableViewCell子类中,我将一个子视图添加到backgroundView:

-(void)method {
    [self.backgroundView addSubview:self.backView];
    [self setConstraintsForBackView];
}

-(UIView*)backView {
    if (!_backView) {
        _backView = [[UIView alloc] initWithFrame:CGRectZero];
    }
    return _backView;
}

我正在尝试使用backView调整backgroundView的大小。我认为使用NSLayoutConstraints是最好的方法,但backView总是出现原始的44点单元格高度,而不是我为每个单元格设置的实际高度。这是我的NSLayoutConstraints的代码

-(void)setConstraintsForBackView {
    [self.backView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|[view]|"
                                                                          options:0
                                                                          metrics:nil
                                                                            views:@{@"view": self.backView}]];
}

我看到以下错误:

'Unable to install constraint on view. Does the constraint reference something from outside the subtree of the view? That's illegal. constraint:<NSLayoutConstraint:0x89662d0 V:|-(0)-[UIView:0x8e87c10] (Names: '|':UIView:0x8e876c0 )> view:<UIView: 0x8e87c10; frame = (0 0; 0 0); layer = <CALayer: 0x8e87c70>>'

我也没试过@"V:|-0-[view]-0-|"

不可否认,我对NSLayoutConstraints没有多少经验,但玩各种视觉格式不会产生任何结果。

1 个答案:

答案 0 :(得分:0)

您需要将约束添加到self.backgroundView而不是self.backView

首先:self.backView.translatesAutoresizingMaskIntoConstraints = NO;

ie:[self.backgroundView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|[view]|" options:0 metrics:nil views:@{@"view": self.backView}]];

相关问题