我一直无法找到我遇到的这个问题的答案。
我在 UIScrollView 中有一个 UIImageView,我希望将其内容垂直居中。
目前,我能够做到这一点的唯一方法是根据 UIImageView 大小的高度设置滚动视图的 contentInset,但这不是一个完美的解决方案;它只是增加了 UIImageView 的大小,使 UIScrollView “认为”其内容更大,并将这些黑条添加到顶部。
我尝试从以下方面获得帮助:
UIScrollView 与居中的 UIImageView,如照片应用程序 https://stackoverflow.com/questions/638299/uiscrollview-with-centered-uiimageview-like-photos-app
and
较小时 UIScrollView 的中心内容 https://stackoverflow.com/questions/1316451/center-content-of-uiscrollview-when-smaller
但无法使用这些答案来解决它。
这段代码应该适用于大多数版本的 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;
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)