本文介绍了在其父视图中垂直和水平居中UIView的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个UICollection视图在另一个UIView中。我试图将集合视图置于其父视图中。目前通过调整其框架手动执行此操作(请参阅下面的代码)。必须有一个更简单的方法。
I have a UICollection view that is inside another UIView. I am trying to center the collection view inside its parent view. Currently manually doing it by tweaking its frame (see code below). There has to be a easier way.
当前代码:
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)
使用这种方法,无论超视图的坐标如何,您的子视图都将以其超视图为中心。使用这样的方法:
With this approach, your subview will be centered in its superview regardless of the superview's coordinates. Using an approach like this:
self.collectionView.center = superview.center
如果superview的原点不是0,0
Will cause problems if the superview has an origin of anything other than 0,0
这篇关于在其父视图中垂直和水平居中UIView的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!