使用Autolayout在自定义UITableViewCell上分页UIScrollView

时间:2014-12-29 22:00:26

标签: ios uitableview uiview uiscrollview autolayout

我正在尝试使用Autolayout在我的自定义UIScrollView中使用横向分页UITableViewCell。我已成功将UIScrollView添加到具有所有适当约束的单元格中。enter image description here

当我尝试使用视图加载UIScrollView时出现问题。我正在覆盖自定义单元格的layoutSubviews方法并在那里加载ScrollView的视图,因为它是我可以找到的唯一方法,其中加载了Autolayout的约束。因此,给我准确的参考ScrollView的大小。

-(void)layoutSubviews {

    [super layoutSubviews];

    for(int i=0; i<self.scrollArray.count; i++) {
        CGRect frame;
        CGFloat width = self.theScrollView.frame.size.width;
        frame.origin.x = width * i;
        frame.origin.y = 0;
        frame.size = self.theScrollView.frame.size;

        UIView *subview = [[UIView alloc] initWithFrame:frame];
        [subview addSubview:[self.scrollArray objectAtIndex:i]];
        [self.theScrollView addSubview:subview];
    }

    CGSize contentSize = CGSizeMake(self.theScrollView.frame.size.width * self.scrollArray.count, self.theScrollView.frame.size.height);
    self.theScrollView.contentSize = contentSize;
    self.theScrollView.contentOffset = CGPointMake(0, 0);
} 

但是,我的单元格会多次调用layoutSubviews,因此会向我的UIScrollView添加超出必要的子视图。是否有更好的方法来加载我不知道的子视图?或者有没有办法使用layoutSubviews,但要确保我的子视图只加载到UIScrollView一次?

1 个答案:

答案 0 :(得分:1)

将添加子视图的部分移动到滚动视图,以设置scrollArray,并将子视图添加到子视图数组属性。在layoutsubviews中,您应该只处理设置框架。

- (void)layoutSubviews
{
    [super layoutSubviews];

    //    self.theScrollView.frame = Make sure you set the scroll view frame;
    for(int i=0; i<self.scrollArray.count; i++) 
    {
        UIView *aView = [self.scrollArray objectAtIndex:i];
        aView.frame = CGRectMake(self.theScrollView.frame.size.width * i, 0, self.theScrollView.frame.size.width, self.theScrollView.frame.size.height);
    }

    self.theScrollView.contentSize = CGSizeMake(self.theScrollView.frame.size.width * self.scrollArray.count, self.theScrollView.frame.size.height);
    self.theScrollView.contentOffset = CGPointMake(0, 0);

}

- (void)partWhereYouSetScrollArray
{
    for(int i=0; i<self.scrollArray.count; i++)
    {
        [self.theScrollView addSubview:[self.scrollArray objectAtIndex:i]];
    }
}

- (void)prepareForReuse
{
   [super prepareForReuse];
   [[self.theScrollView subviews] makeObjectsPerformSelector:@selector(removeFromSuperview)];
   [self.scrollArray removeAllObjects];
}
相关问题