ios - 将 UIView 在其父 View 中垂直和水平居中

标签 ios objective-c uiview uicollectionview frame

我有一个位于另一个 UIView 中的 UICollection View 。我正在尝试将 Collection View 置于其父 View 的中心。目前通过调整其框架手动完成(参见下面的代码)。必须有更简单的方法。

当前代码:

self.collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(COLLECTION_PADDING+10, COLLECTION_PADDING+5, self.bounds.size.width - (COLLECTION_PADDING*2), self.bounds.size.height - (COLLECTION_PADDING+22)) collectionViewLayout:flow];

最佳答案

你可以这样做:

self.collectionView.center = CGPointMake(CGRectGetMidX(superview.bounds), CGRectGetMidY(superview.bounds));

swift 3:

self.collectionView.center = CGPoint(superview.bounds.midX, superview.bounds.midY)

使用这种方法,无论父 View 的坐标如何,您的 subview 都将在其父 View 中居中。使用这样的方法:

self.collectionView.center = superview.center

如果父 View 的原点不是 0,0 就会导致问题

关于ios - 将 UIView 在其父 View 中垂直和水平居中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24957986/

相关文章:

Swift 中可编码属性的 iOS 通用类型

iphone - 使用 CALayer 作为 subview 的动画 UIView 框架

android - 如何在检索 ListView 的项目时显示 "Loading..."文本

iphone - 在 iOS 中读取文本文件中的 url 后加载 NSURL?

iOS - [UIView setAnimationDidStopSelector :@selector(animationDidStop:finished:context:)] called too soon

ios - 我可以烘焙/展平 UIImageView,包括它的圆角层和 masksToBounds

ios - 单元格一开始不出现,但如果我向下滚动并返回,则会显示

ios - 这个散列保证是唯一的吗?

IOS :the image is not appearing properly in uiimage when its size is larger or smaller

ios - 如何在 ios 10 中处理后台推送通知?