How to center content in a UIScrollView with conte

2019-03-24 04:47发布

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?

4条回答
我想做一个坏孩纸
2楼-- · 2019-03-24 05:08

I think you want:

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

diagram:

|------------------------self.contentSize.width------------------------|
                         |-----self.width-----|
|-------- offset --------|
                                    ^ center
查看更多
ら.Afraid
3楼-- · 2019-03-24 05:13

Use below code:

CGFloat newContentOffsetX = (scrollView.contentSize.width - scrollView.frame.size.width) / 2;
scrollView.contentOffset = CGPointMake(newContentOffsetX, 0);
查看更多
再贱就再见
4楼-- · 2019-03-24 05:26

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)
查看更多
淡お忘
5楼-- · 2019-03-24 05:27

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];
}
查看更多
登录 后发表回答