2

我在我的 UIViewController 中放入了一个 UIScrollView 到我的故事板中。当我使用此代码时:

- (void)viewDidLoad
{
    [super viewDidLoad];

    [_scrollview setContentSize:CGSizeMake(_scrollview.bounds.size.width*2, _scrollview.bounds.size.height)];
    [_scrollview setPagingEnabled:YES];

    CGRect rect = _scrollview.bounds;

    UIView* view = [[UIView alloc]initWithFrame:rect];
    [view setBackgroundColor:[UIColor redColor]];
    [_scrollview addSubview:view];

    rect = CGRectOffset(rect, _scrollview.bounds.size.width, 0);
    view = [[UIView alloc]initWithFrame:rect];
    view.backgroundColor = [UIColor greenColor];
    [_scrollview addSubview:view];

}

没有自动布局也可以正常工作,但是当我启用时,“rect”值等于 0。自动布局的等效代码是什么?

4

1 回答 1

6

似乎您在自动布局环境中缺少一些关于 UIScrollView 的基本内容。仔细阅读ios 6.0 发行说明

您的代码应如下所示:

- (void)viewDidLoad
{
    [super viewDidLoad];

    CGRect selfBounds = self.view.bounds;
    CGFloat width = CGRectGetWidth(self.view.bounds);
    CGFloat height = CGRectGetHeight(self.view.bounds);
    [_scrollview setPagingEnabled:YES];

    UIView* view1 = [[UIView alloc] initWithFrame:selfBounds];
    [view1 setTranslatesAutoresizingMaskIntoConstraints:NO];
    [view1 setBackgroundColor:[UIColor redColor]];
    [_scrollview addSubview:view1];

    UIView* view2 = [[UIView alloc]initWithFrame:CGRectOffset(selfBounds, width, 0)];
    [view2 setTranslatesAutoresizingMaskIntoConstraints:NO];
    view2.backgroundColor = [UIColor greenColor];
    [_scrollview addSubview:view2];

    [_scrollview addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"|[view1(width)][view2(width)]|" options:0 metrics:@{@"width":@(width)} views:NSDictionaryOfVariableBindings(view1,view2)]];
    [_scrollview addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|[view1(height)]|" options:0 metrics:@{@"height":@(height)} views:NSDictionaryOfVariableBindings(view1)]];
    [_scrollview addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|[view2(height)]|" options:0 metrics:@{@"height":@(height)} views:NSDictionaryOfVariableBindings(view2)]];
}
于 2013-03-01T11:41:14.810 回答