0

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

这是我的代码:

-(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];


}

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

4

1 回答 1

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]];
于 2013-10-18T12:58:49.097 回答