我的 UIScrollView 不适用于 ios6 中的自动布局 [英] My UIScrollView doesn't work with auto-layout in ios6

查看:23
本文介绍了我的 UIScrollView 不适用于 ios6 中的自动布局的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已将 UIViewController 中的 UIScrollView 放入我的情节提要中.当我使用此代码时:

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

}

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

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 ?

推荐答案

好像你在自动布局环境中遗漏了一些关于 UIScrollView 的基本知识.仔细阅读 ios 6.0 发行说明

Seems that you are missing some basic stuff about UIScrollView in autolayout environment. Read carefully 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)]];
}

这篇关于我的 UIScrollView 不适用于 ios6 中的自动布局的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆