My UIScrollView doesn't work with auto-layout in ios6

后端 未结 1 1168
旧巷少年郎
旧巷少年郎 2021-01-07 01:33

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

- (void)viewDidLoad
{
    [super viewDidLoad];

    [_scrollview          


        
1条回答
  •  轻奢々
    轻奢々 (楼主)
    2021-01-07 01:59

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

    0 讨论(0)
提交回复
热议问题