UIScrollView do not scroll

守給你的承諾、 提交于 2019-12-12 11:56:51

问题


I have a UIScrollView that do not scroll at all. If I enable bouncing, I can scroll far enough to the sides to see that there is content outside of the view, but it snaps right back to the origin when I release. I have paging turned on, but I get the same behavior if I turn it off. I have auto layout turned off. In the IB, the scrollView is in a MainViewController, correctly linked up to the IBOutlet as below.

@interface MainViewController ()

@property (strong, nonatomic) IBOutlet UIScrollView *scrollView;

@end

@implementation MainViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    for (int i = 0; i < 3; i++) {
        CGRect frame;
        frame.origin.x = self.scrollView.frame.size.width * i;
        frame.origin.y = 0;
        frame.size = self.scrollView.frame.size;

        // I might be doing this wrong, but it returns a PosterView object just like I want it to.
        NSArray *view = [[NSBundle mainBundle] loadNibNamed:@"posterView" owner:self options:nil];
        [[view objectAtIndex:0] setFrame:frame];

        [self.scrollView addSubview:[view objectAtIndex:0]];
    }

    self.scrollView.contentSize = CGSizeMake(self.scrollView.frame.size.width * 3, self.scrollView.frame.size.height);
}

If I use this method though, it scrolls correctly.

-(void)scrollToPage:(NSInteger)page{
    float pageWidth = [self.scrollView frame].size.width;
    [self.scrollView setContentOffset:CGPointMake(page*pageWidth,0) animated:YES];
}

I have tried implementing the UIScrollViewDelegate and overriding scrollViewDidScroll, but it is never called (unless I have enable bouncing, like I mentioned earlier).


回答1:


UIScrollView only scrolls when having a contentSize larger than its frame size. If it doesn't scroll might mean that its contentSize is not large enough. So check what its contentSize is after setting it.

If the contentSize is as you are expecting it to be then check for if the scrollView is scrollEnabled or not. Sometimes enabling bounce creates an impression that the scrolling is working. Also, if the scrolling is not enabled,setting the contentOffset works in that case too because then it moves the content according to the provided size as argument.




回答2:


You should set the contentSize inside viewDidLayoutSubviews. It is late enough in the view life cycle for it not to be reset by any other method, and doesn't require you to check whether the view is scrolling for the first time.



来源:https://stackoverflow.com/questions/17475487/uiscrollview-do-not-scroll

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!