My UIScrollView doesn't work with auto-layout

2020-03-06 18:38发布

问题:

I have put an UIScrollView in my UIViewController into my storyboard. When I use this code:

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

}

It's works fine without auto-layout, but when I enable, "rect" values is equals to 0. What is the equivalent code with auto-layout ?

回答1:

Seems that you are missing some basic stuff about UIScrollView in autolayout environment. Read carefully ios 6.0 release notes

Your code should look like:

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