I just can't get my scroll view to actually scroll.. Everything displays fine except it just won't scroll..... Here's my code:
- (void)viewDidLoad {
[super viewDidLoad];
UIScrollView *scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, 320, 600)];
scrollView.contentSize = CGSizeMake(320, 600);
scrollView.scrollEnabled = YES;
scrollView.clipsToBounds = YES;
[self.view addSubview:scrollView];
planView = [[WorkoutPlanView alloc] initWithImage:[UIImage imageNamed:@"WorkoutTable.png"]];
planView2 = [[WorkoutPlanView alloc] initWithImage:[UIImage imageNamed:@"WorkoutTable.png"]];
planView2.frame = CGRectMake(0, 164, 320, 165);
planView3 = [[WorkoutPlanView alloc] initWithImage:[UIImage imageNamed:@"WorkoutTable.png"]];
planView3.frame = CGRectMake(0, 328, 320, 165);
planView4 = [[WorkoutPlanView alloc] initWithImage:[UIImage imageNamed:@"WorkoutTable.png"]];
planView4.frame = CGRectMake(0, 505, 320, 165);
[scrollView addSubview:planView];
[scrollView addSubview:planView2];
[scrollView addSubview:planView3];
[scrollView addSubview:planView4];
}
How do I fix this problem?
The idea of why scroll view is not scrolling because you set the content size for scrolling less than the size of the scroll view, which is wrong. You should set the content size bigger than the size of your scroll view to navigate through it while scrolling.
Therefore set the width of the content view to be the width of the scroll view. Attach four constraints (top, bottom, left, right) from our single content view to the scroll view. Make sure you have constraints attached to all four sides of the content view so that it will expand to the size of your content.
In most cases to scroll vertically. Therefore set the width of the content view to be the width of the scroll view. Attach four constraints (top, bottom, left, right) from our single content view to the scroll view. Make sure you have constraints attached to all four sides of the content view so that it will expand to the size of your content.
And to make it work, the contentview should have a fixed size. The trick to the fixed size is that you can set the width of the contentview equal to that of the scrollview's parent. Just select both views in the tree on the left and add the equal widths constraint. This is the gist of that article.
The contentSize
must be larger than the scrollview's frame for there to be anything to scroll. :)
In this case, they're both (320, 600)
so change your scrollView's init to
UIScrollView *scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, 320, 480)];
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With