我的UIScrollView不与iOS6的自动布局工作(My UIScrollView doesn&

2019-07-20 18:32发布

我已经把一个UIScrollView的在我的UIViewController到我的故事板。 当我使用此代码:

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

}

它工作正常,没有自动布局,但是当我使,“矩形”值是等于0。什么是自动布局的等同的代码?

Answer 1:

看来你是缺少有关的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)]];
}


文章来源: My UIScrollView doesn't work with auto-layout in ios6