-->

contentOffset is reset on ScrollView header when v

2019-07-02 19:06发布

问题:

Im making use of this code to align a load of truckDayScrollViews (Subclass of UIScrollView) horizontally in a UITableView, SUDaysForTruckView is just a custom UILabel

-(void)scrollViewDidScroll:(UIScrollView *)scrollView
{

    if ([scrollView isKindOfClass:[SUDaysForTruckView class]]) {
        CGPoint offset=CGPointMake(scrollView.contentOffset.x, 0);
        for (TruckViewCell *cell in self.tableView.visibleCells) {
            cell.truckDayScrollView.contentOffset=offset;

        }
        self.headerView.contentOffset=offset;
        self.scrollViewPosition=offset;
    }
    else{
        NSLog(@"Table view scrolling vertically: %f,%f",self.scrollViewPosition.x,self.scrollViewPosition.y);
        self.headerView.contentOffset=self.scrollViewPosition;
    }
}

The idea being, that if the class of the scrolling scroll view is part of the cell (scrolling horizontally) then update all the scrollviews, including the header. This works great.

Although when the tableView scrolls vertically, the content offset in the header scroll view is reset to 0,0.

Why is this, and is there a way to fix it. I have tried putting the line

    self.headerView.contentOffset=self.scrollViewPosition;

in so many places cellForRow, the getter for self.headerView,etc. all to no avail.

The first picture shows horizontal scrolling and how the header is aligned, the second picture shows what happens on the very first bit of vertical scrolling, the headers jump out of alignment immediately.

回答1:

I ended up overriding drawRect: I get the current content offset of the scrollViews before vertical scrolling. And then I needed a little bit extra to stop all my views having a black background.

- (void)drawRect:(CGRect)rect
{
     [super drawRect:rect];
    CGContextRef ctx = UIGraphicsGetCurrentContext();
    CGFloat white[] = {1, 1, 1, 1};
    CGContextSetFillColor(ctx, white);
    CGContextAddRect(ctx, rect);
    CGContextFillPath(ctx);
    self.contentOffset=[self.scrollViewMaster scrollViewPosition];
}