UIScrollView child jumping after UINavigationContr

2019-04-30 01:49发布

So I have a UIScrollView on my iPad app with a single child view (which itself is parent to all the controls). The scrolling all works fine on it. Rotating works fine (the whole view fits in portrait, scrolls on landscape). Once pushing a new screen on the UINavigationController, and then coming back breaks it.

It looks as if the frame of the scrollview's child has moved up, relative to the scroll position, but the scrollview has remained at the bottom (the entire child view has shifted upwards).

I've tried fighting the Constraints in storyboard, literally for hours, and cannot work out what could be causing this.

How it starts How it looks like after navigating and returning

3条回答
Bombasti
2楼-- · 2019-04-30 02:23

Here is a simple solution i found. (Assuming the parent view is meant to span the entire contentSize) Use this subclass of UIScrollView:

@interface BugFixScrollView : UIScrollView
@end
@implementation BugFixScrollView
-(void)layoutSubviews
{
    [super layoutSubviews];
    UIView *view=[self.subviews firstObject];
    if(view)
    {
        CGRect rect=view.frame;
        rect.origin=CGPointMake(0, 0);
        view.frame=rect;
    }
}
@end

It simply resets the origin every time auto-layout messes it up. this class can be used in InterfaceBuilder simply by changing the class name after placing the UIScrollView.

查看更多
劳资没心,怎么记你
3楼-- · 2019-04-30 02:32

Get the frame of the subview before it disappears then manually reset the frame of the subview every time the view appears in -(void)viewWillAppear:(BOOL)animated.

-(void)viewWillDisappear:(BOOL)animated{
[super viewWillDisappear:animated];
globalFrameVariable = subview.frame;
[subview removeFromSuperview];
}

-(void)viewWillAppear:(BOOL)animated{
[super viewWillAppear:animated];
[subview setFrame:globalFrameVariable];
[scrollView addSubview:subview];
}
查看更多
Melony?
4楼-- · 2019-04-30 02:46

I had the same problem with scroll view and auto layouts (iOS 6 - doesn't work, iOS 7 - works fine), of course this is not perfect solution, but seems like it works. Hope it will help you:

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];

    [self performSelector:@selector(content) withObject:nil afterDelay:0.0];
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];

    offset = self.scrollView.contentOffset;
}

- (void)viewDidDisappear:(BOOL)animated
{
   [super viewDidDisappear:animated];

   self.scrollView.contentOffset = CGPointZero;
}

- (void)content
{
    [self.scrollView setContentOffset:offset animated:NO];
}
查看更多
登录 后发表回答