在其父视图中垂直和水平居中UIView

jdo*_*dog 5 objective-c frame uiview ios uicollectionview

我有一个UICollection视图在另一个UIView中.我试图将集合视图置于其父视图中.目前通过调整其框架手动执行此操作(请参阅下面的代码).必须有一个更简单的方法.

当前代码:

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];
Run Code Online (Sandbox Code Playgroud)

Log*_*gan 24

你可以这样做:

self.collectionView.center = CGPointMake(CGRectGetMidX(superview.bounds), CGRectGetMidY(superview.bounds));
Run Code Online (Sandbox Code Playgroud)

斯威夫特3:

self.collectionView.center = CGPoint(superview.bounds.midX, superview.bounds.midY)
Run Code Online (Sandbox Code Playgroud)

使用这种方法,无论superview的坐标如何,您的子视图都将以其超视图为中心.使用这样的方法:

self.collectionView.center = superview.center
Run Code Online (Sandbox Code Playgroud)

如果superview的原点不是0,0,则会导致问题