【问题标题】:Creating a view programmatically with frame based on another view created in Storyboard with Auto-layout基于在 Storyboard 中使用自动布局创建的另一个视图,以编程方式使用框架创建视图
【发布时间】:2015-10-24 23:00:48
【问题描述】:

我在 Storyboard 中添加了一个滚动视图,并在 Storyboard 中设置了它的自动布局属性。所以很明显它在不同的 iPhone 上需要不同的尺寸,这正是我想要的。现在我想在滚动视图中添加两个子视图,每个子视图占据滚动视图的整个可见区域并启用分页。因此,在任何时候,其中一个子视图都是可见的,您可以向左或向右滑动以查看另一个子视图。

我的问题是,由于我在程序中创建这两个视图,我不确定应该在哪里设置子视图框架。这就是我现在在 viewDidLayoutSubviews 中所做的,但理想情况下我想在 viewDidload 中执行此操作,但在 viewDidLoad 中尚未设置框架:

@interface ViewController () 
   @property (weak, nonatomic) IBOutlet UIScrollView *scrollView;
   @property (nonatomic, strong) UIView *pageOne;
   @property (nonatomic, strong) UIView *pageTwo;
@end

- (void) viewDidLayoutSubviews

{
    self.scrollView.pagingEnabled = YES;
    self.pageOne = [[UIView alloc] initWithFrame: CGRectMake(0, 0, self.scrollView.bounds.size.width, self.scrollView.bounds.size.height)];
self.pageOne.backgroundColor = [UIColor redColor];
    [self.scrollView addSubview:self.pageOne];

    self.pageTwo = [[UIView alloc] initWithFrame: CGRectMake(self.scrollView.bounds.size.width, 0, self.scrollView.bounds.size.width, self.scrollView.bounds.size.height)];
    self.pageTwo.backgroundColor = [UIColor blueColor];
    [self.scrollView addSubview:self.pageTwo];


    self.statsScrollView.contentSize = CGSizeMake(self.scrollView.bounds.size.width * 2, self.scrollView.bounds.size.height);
}

所以,我的问题是,如果我在程序中创建的视图(上面的 pageOne 和 pageTwo)是指在 Storyboard 中设置的视图的框架,并且它们的大小具有自动布局,我应该在哪里设置代码。我知道我的代码存在多次执行的问题,这不是我想要的。

【问题讨论】:

    标签: ios objective-c iphone uiscrollview ios-autolayout


    【解决方案1】:

    您必须等到实际布局完成才能抓取框架,因此viewDidLayoutSubviews 是一个不错的选择。如果你想确保页面只添加一次,你可以简单地检查它们是否已经被初始化,如下所示:

    if (!self.pageOne) {
        self.pageOne = [[UIView alloc] initWithFrame: CGRectMake(0, 0, self.scrollView.bounds.size.width, self.scrollView.bounds.size.height)];
        self.pageOne.backgroundColor = [UIColor redColor];
        [self.scrollView addSubview:self.pageOne];
    }
    

    当然,您也可以在 viewDidLoad 方法中使用 CGRectZero 框架初始化页面并将它们添加为子视图,然后稍后设置适当的框架,即:

    viewDidLoad:

    self.pageOne = [[UIView alloc] initWithFrame: CGRectZero];
    self.pageOne.backgroundColor = [UIColor redColor];
    [self.scrollView addSubview:self.pageOne];
    

    viewDidLayoutSubviews:

    self.pageOne.frame = CGRectMake(0, 0, self.scrollView.bounds.size.width, self.scrollView.bounds.size.height);
    

    【讨论】:

    • 第一个解决方案不起作用,因为 viewDidLayoutSubviews 被多次调用,第一次被调用并不能保证 self.scrollView.bounds 有它的最终值,事实上我的情况确实如此不是,因此第一个解决方案会将 self.pageOne 框架修复为不正确的值。但第二种解决方案奏效了。谢谢。
    猜你喜欢
    • 1970-01-01
    • 2018-08-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-07
    • 1970-01-01
    • 2018-07-06
    • 1970-01-01
    相关资源
    最近更新 更多