Im developing an iPad app in which I have a scrollview, the size of which i determine dynamically depending on the number of objects i display in it. Now, though i have not set any content offset I find that the scroll view has been offset by some amount whenever the view loads. When I check the value of the offset, it shows 0. I dont understand why without having a contentOffset value, the scrollview behaves that way. Any reasons for this?
I suspect this has something to do with iOS 4.2 as i dont remember this problem occurring when i was testing the app on iOS 3.2.
Update: The amount its getting offset seems to vary based on the contentSize of the scrollView. If the contentSize of the scrollView matches that of its frame height (its a vertical scrollview), then there is no offset. As the contentSize increases above the value of the height of the scrollView frame, the offset also increases proportionally. However, scrollView.contentOffset.y still = 0.0
if u use interface builder -
- add scrollview to the view
- create another view and add elements that u need to add to scroll view
then add this second view to scrollview
write this code in Viewdidload
scrollview.contentsize.y = lastelement.frame.origin.y + lastelement.frame.size.height + 10
this will adjust the scrollview to content size. it displays the first element and can scroll from top to bottom.
The UIScrollView definitively does not behave the same way on iPad with iOS 4.2.1 than in iOS 3.
I don't yet know if it's a bug or if I missed something in the documentation about an evolution.
My scrollview was created in a xib and I was reusing it to display different object of the same class. In my code, I only modified the contentSize of this scrollview.
The offset remained at 0 when looking with NSLog, but was varying on screen.
To fix my problem, I ended up creating programmatically a new scrollview each time I was displaying a new object. Might not be possible in your case, but for me, problem solved worked around.
I faced same problem. Solved by keeping code for setting scrollview in viewWillAppear:animated
-(void) viewWillAppear:(BOOL)animated
{
scrollView.frame = self.view.frame;
scrollView.contentSize = self.view.frame.size;
}
If you use Auto Layout and want to set the offset for the scroll view contents, this is what worked for me:
- (void)viewDidLayoutSubviews {
[super viewDidLayoutSubviews];
self.myScrollView.contentOffset = CGPointMake(500, 0);
}
Assign the sum of frame.origin
value and frame.height
value of last element to scrollView.contentOffset.y
Also in Swift
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
scrollView.contentOffset = CGPointZero
}