iosobjective-cuiscrollview

How to center content in a UIScrollView with contentOffset


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?


Solution

  • I think you want:

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

    diagram:

    |------------------------self.contentSize.width------------------------|
                             |-----self.width-----|
    |-------- offset --------|
                                        ^ center