无法显示控件使用自动布局添加滚动视图的内容视图

时间:2013-10-18 12:34:57

标签: iphone ios ipad nslayoutconstraint nsautolayout

我是汽车布局部分的新手。我正在以编程方式创建一个带有滚动的视图,但我无法在滚动视图的内容视图中添加控件

这是我的代码:

-(void)setConstraints
{

    UIScrollView *scrollView = [UIScrollView new];
    [scrollView setTranslatesAutoresizingMaskIntoConstraints:NO];
    scrollView.backgroundColor = [UIColor greenColor];

    UIView *contentView = [UIView new];
    [contentView setTranslatesAutoresizingMaskIntoConstraints:NO];
    contentView.backgroundColor = [UIColor redColor];

    UILabel *lableTitle = [UILabel new];
    lableTitle.text = @"Registration";
    [lableTitle setTranslatesAutoresizingMaskIntoConstraints:NO];
    NSLayoutConstraint *layoutLableTop = [NSLayoutConstraint constraintWithItem:lableTitle attribute:NSLayoutAttributeTop relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeTop multiplier:1 constant:20];
    [self.view  addConstraint:layoutLableTop];

    NSLayoutConstraint *layoutLableCenterX = [NSLayoutConstraint constraintWithItem:lableTitle attribute:NSLayoutAttributeCenterX relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeCenterX multiplier:1 constant:0];
    [self.view addConstraint:layoutLableCenterX];

    [contentView  addSubview:lableTitle];
    [scrollView addSubview:contentView];

    [self.view addSubview:scrollView];


}

显示的视图只是白色屏幕。我做错了什么?

1 个答案:

答案 0 :(得分:1)

您必须为尺寸添加约束,例如

[self.view addConstraint:
 [NSLayoutConstraint constraintWithItem:scrollView
                              attribute:NSLayoutAttributeWidth
                              relatedBy:NSLayoutRelationEqual
                                 toItem:contentView
                              attribute:NSLayoutAttributeWidth
                             multiplier:1
                               constant:200]];
[self.view addConstraint:
 [NSLayoutConstraint constraintWithItem:scrollView
                              attribute:NSLayoutAttributeHeight
                              relatedBy:NSLayoutRelationEqual
                                 toItem:contentView
                              attribute:NSLayoutAttributeHeight
                             multiplier:1
                               constant:200]];