How to center content in a UIScrollView with contentOffset How to center content in a UIScrollView with contentOffset ios ios

How to center content in a UIScrollView with contentOffset


I think you want:

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

diagram:

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


Use below code:

CGFloat newContentOffsetX = (scrollView.contentSize.width - scrollView.frame.size.width) / 2;scrollView.contentOffset = CGPointMake(newContentOffsetX, 0);


Swift 4

Scroll to center of content of ScrollView

let centerOffsetX = (scrollView.contentSize.width - scrollView.frame.size.width) / 2let centerOffsetY = (scrollView.contentSize.height - scrollView.frame.size.height) / 2let centerPoint = CGPoint(x: centerOffsetX, y: centerOffsetY)scrollView.setContentOffset(centerPoint, animated: true)