Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to center content in a UIScrollView with contentOffset

Tags:

This should be a VERY easy problem but I'm having trouble getting the desired result. I have horizontally scrolling UIScrollView with a width of 320. The width of its content is 5000. I'm trying to center the content with:

// 'self' is the UIScrollView CGFloat newContentOffsetX = (self.width/2) + (self.contentSize.width/2); self.contentOffset = CGPointMake(newContentOffsetX, 0); 

I don't understand why this is not centering the content. Can you see something wrong with the calculations?

like image 402
zakdances Avatar asked Mar 23 '13 04:03

zakdances


People also ask

What is scroll view in Swift?

The scroll view displays its content within the scrollable content region. As the user performs platform-appropriate scroll gestures, the scroll view adjusts what portion of the underlying content is visible. ScrollView can scroll horizontally, vertically, or both, but does not provide zooming functionality.


1 Answers

I think you want:

CGFloat newContentOffsetX = (self.contentSize.width/2) - (self.bounds.size.width/2); 

diagram:

|------------------------self.contentSize.width------------------------|                          |-----self.width-----| |-------- offset --------|                                     ^ center 
like image 161
Isaac Avatar answered Feb 02 '23 01:02

Isaac