I faced a strange problem, the scrollview does not scroll down, only scroll up. I have scrollview in my app, please look at my coding
.....
self.scrollView = [[UIScrollView alloc] initWithFrame: CGRectMake(0, 0, 320,427)];
[self.view addSubViews: self.scrollView];
UIView *blueView = [[UIView alloc] initWithFrame: CGRectMake(0, 47, 320, 320)];
blueView.backgroundColor = [UIColor blueColor];
[self.scrollView addSubViews: blueView];
self.scrollView.contentSize = CGSize(320, 640);
....
My problem is no matter what value I changed contentSize, my ScrollView only scroll up, not scroll down. I want user can move blueView to the top or bottom of iPhone screen from the original position.
do you have this problem?
The Problem
It looks like your issue is with how you’re orienting
blueViewwithinscrollView. You’re setting the frame ofblueViewto theCGRect(0, 47, 320, 320). When you set the frame like this, one of the things you’re implicitly saying is:That’s a perfectly valid thing to say, but it’s what’s causing the problem you describe.
scrollViewwon’t scroll down because it is designed to start, by default, with the rect(0, 0, 320, 480)in view. ThecontentSizeproperty only indicates the size of the content within theUIScrollView, not its positioning. When you set it, you’re basically tellingscrollView:Thus,
scrollViewwon’t scroll up because, as far as it knows, there’s no content above the coordinate(0, 0).The Solution
There are three steps you’ll need to take to get the functionality you want.
contentSizeto be just big enough to allowblueViewto scroll all the way up and down.blueViewin the vertical center ofscrollView.scrollViewso that it is initially centered onblueView.contentSizeto be just big enough to allowblueViewto scroll all the way up and down.We’ll want to calculate the correct value of the
contentSizeproperty. It is of the typeCGSize, so we need two parts:widthandheight.widthis easy – since you don’t seem to want horizontal scrolling, just make it the width of the screen,320. Height is a little more tricky. If you wantblueViewto just touch the top and bottom of the screen when scrolled up or down, you need to do some math. The correct total height will be double the height of the screen, minus the height ofblueView. So:blueViewin the vertical center ofscrollView.That’s easy; just set the
centerproperty of blueView:scrollViewso that it is initially centered onblueView.If you check the Apple UIScrollView documentation, you’ll see an instance method
- (void)scrollRectToVisible:(CGRect)rect animated:(BOOL)animated. This is exactly what you need to scrollscrollViewprogrammatically. The rect you want is the one centered onblueView, with the size of the iPhone screen. So:Make sure you do this scrolling in
viewWillAppear, so it’s ready right when the user sees the view.That should be it. Let me know if you have any questions!