[英]Trying to center a view within its superview
I am creating a category on UIView
to make programmatically positioning and sizing my views easier. 我在
UIView
上创建了一个类别,以方便地以编程方式定位和调整视图大小。 I want to create a method that will center a given view horizontally or vertically in its superview
. 我想创建一个方法,将给定视图在其
superview
视图中水平或垂直居中。 So I can do something like the following: 因此,我可以执行以下操作:
Category 类别
- (void)centerHorizontally {
self.center = CGPointMake(self.window.superview.center.x, self.center.y);
}
- (void)centerVertically {
self.center = CGPointMake(self.center.x, self.window.superview.center.y);
}
Use 采用
UIView *v = [[UIView alloc] initWithFrame:CGRectMake(0,0,100,100)];
[v centerHorizontally];
However, this doesn't seem to be working. 但是,这似乎不起作用。 What is incorrect about my solution?
我的解决方案有何不正确之处?
You need to add the view to a parent view before you can center it. 您需要先将视图添加到父视图,然后才能将其居中。
UIView *v = [[UIView alloc] initWithFrame:CGRectMake(0,0,100,100)];
[someOtherView addSubview:v];
[v centerHorizontally];
And your category is incorrect. 您的类别不正确。 Don't get the window involved.
不要牵扯到窗户。 You need to base it on the superview's size:
您需要基于超级视图的大小:
- (void)centerHorizontally {
self.center = CGPointMake(self.superview.bounds.size.width / 2.0, self.center.y);
// or
self.center = CGPointMake(CGRectGetMidX(self.superview.bounds), self.center.y);
}
- (void)centerVertically {
self.center = CGPointMake(self.center.x, self.superview.bounds.size.height / 2.0);
// or
self.center = CGPointMake(self.center.x, CGRectGetMidY(self.superview.bounds));
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.