How to center content in a UIScrollView with conte

2019-03-24 05:19发布

问题:

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?

回答1:

I think you want:

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

diagram:

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


回答2:

Use below code:

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


回答3:

Swift 4

Scroll to center of content of ScrollView

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


回答4:

Not the best solution but might work for you

- (void)viewDidLayoutSubviews {
    [super viewDidLayoutSubviews];
    [self centerScrollViewAnimated:NO];
}

- (void)scrollViewDidEndZooming:(UIScrollView *)scrollView withView:(UIView *)view atScale:(CGFloat)scale {
    [self centerScrollViewAnimated:YES];
}

- (void)scrollViewWillEndDragging:(UIScrollView *)scrollView withVelocity:(CGPoint)velocity targetContentOffset:(inout CGPoint *)targetContentOffset {
    *targetContentOffset = [self suggestedCenteredContentOffset];
}

- (CGPoint)suggestedCenteredContentOffset {
    CGSize imageSize = self.pickedImage.size;
    CGSize containerSize = self.zoomingScrollView.bounds.size;
    CGPoint result = self.zoomingScrollView.contentOffset;

    if ( self.zoomingScrollView.zoomScale * imageSize.width < containerSize.width )
        result.x = MIN((self.zoomingScrollView.zoomScale * imageSize.width - containerSize.width)/2, 0);

    if ( self.zoomingScrollView.zoomScale * imageSize.height < containerSize.height )
        result.y = MIN((self.zoomingScrollView.zoomScale * imageSize.height - containerSize.height)/2, 0);

    return result;
}

- (void)centerScrollViewAnimated:(BOOL)animated {
    [self.zoomingScrollView setContentOffset:[self suggestedCenteredContentOffset] animated:animated];
}