在没有contentInset的UIScrollView中居中UIImageView?

run*_*mad 5 iphone uiscrollview uiimageview

我一直无法找到这个问题的答案.

我在UIScrollView中有一个UIImageView,我希望中心的内容是垂直的.

现在,我能够做到这一点的唯一方法是根据UIImageView大小的高度设置滚动视图的contentInset,但这不是一个完美的解决方案; 它只是增加了UIImageView的大小,使得UIScrollView'认为'它的内容更大,并将这些黑条添加到顶部.

我试图从以下方面获得帮助:

UIScrollView带有居中的UIImageView,就像Photos app一样

UIScrollView的中心内容较小时

但是还没能用这些答案来解决它.

Jos*_*phH 6

此代码应该适用于大多数iOS版本(并且已经过测试,可以在3.1版本上运行,这是我目前可以访问的所有版本).

它基于Jonah的答案中提到的Apple WWDC代码.

将以下内容添加到UIScrollView的子类中,并将tileContainerView替换为包含图像或切片的视图:

- (void)layoutSubviews {
    [super layoutSubviews];

    // center the image as it becomes smaller than the size of the screen
    CGSize boundsSize = self.bounds.size;
    CGRect frameToCenter = tileContainerView.frame;

    // center horizontally
    if (frameToCenter.size.width < boundsSize.width)
        frameToCenter.origin.x = (boundsSize.width - frameToCenter.size.width) / 2;
    else
        frameToCenter.origin.x = 0;

    // center vertically
    if (frameToCenter.size.height < boundsSize.height)
        frameToCenter.origin.y = (boundsSize.height - frameToCenter.size.height) / 2;
    else
        frameToCenter.origin.y = 0;

    tileContainerView.frame = frameToCenter;
}
Run Code Online (Sandbox Code Playgroud)


con*_*are 1

创建一个单独的uiview并添加居中的UIImageView,然后将视图添加到scrollview

UIView *view = [[UIVIew alloc] initWithFrame:<frame that will fill your scrollview>];
CGRect frame = CGRectMake((view.size.width - IMAGE_WIDTH)/2, (view.size.height - IMAGE_HEIGHT)/2, IMAGE_WIDTH, IMAGE_HEIGHT);
UIImageView *imageView = [[UIImageView alloc] initWithFrame:frame];
imageView.image = [UIImage imageNamed:@"imageSized_IMAGE_WIDTH_by_IMAGE_HEIGHT.png"];
[view addSubview:imageView];
[imageView release];

[scrollView addSubview:view];
[view release];
Run Code Online (Sandbox Code Playgroud)

请注意,您需要将视图框架设置为滚动视图中所需的尺寸和位置。需要注意的重要部分是通过使用视图框架尺寸作为变量来使图像视图在视图框架内居中。