是否在UIScrollView内居中UIImageView而没有contentInset? [英] Center UIImageView inside UIScrollView without contentInset?

查看:37
本文介绍了是否在UIScrollView内居中UIImageView而没有contentInset?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have been unable to find the answer for this issue I am having.

我在UIScrollView中有一个UIImageView,我想垂直放置其内容的中心.

I have a UIImageView inside a UIScrollView, and I would like the center its content vertically.

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

Right now, the only way I have been able to do this is by setting the scroll view's contentInset based on the height of the UIImageView size, but this is not a perfect solution; it just increases the size of the UIImageView, making the UIScrollView 'think' its content is bigger, and adds these black bars to the top.

我试图从以下方面寻求帮助:

I've tried to get help from:

具有居中的UIImageView的UIScrollView,例如照片"应用

UIScrollView的中心内容(较小时)

但是无法使用这些答案来解决它.

But have not been able to solve it using those answers.

推荐答案

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

This code should work on most versions of iOS (and has been tested to work on 3.1 upwards, which is all I currently have access to).

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

It's based on the Apple WWDC code mentioned in Jonah's answer.

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

Add the below to your subclass of UIScrollView, and replace tileContainerView with the view containing your image or tiles:

- (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;
}

这篇关于是否在UIScrollView内居中UIImageView而没有contentInset?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆