2013-03-01 37 views
2

我已將UIScrollView放入我的故事板中的UIViewController中。當我使用此代碼:我的UIScrollView無法在ios6中自動佈局

- (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。什麼是自動佈局的等同的代碼?

回答

6

似乎你在自動佈局環境中缺少一些關於UIScrollView的基本知識。請仔細閱讀ios 6.0 release notes

您的代碼應該是這樣的:

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