[英]Trying to center a view within its superview
我在UIView
上创建了一个类别,以方便地以编程方式定位和调整视图大小。 我想创建一个方法,将给定视图在其superview
视图中水平或垂直居中。 因此,我可以执行以下操作:
类别
- (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);
}
采用
UIView *v = [[UIView alloc] initWithFrame:CGRectMake(0,0,100,100)];
[v centerHorizontally];
但是,这似乎不起作用。 我的解决方案有何不正确之处?
您需要先将视图添加到父视图,然后才能将其居中。
UIView *v = [[UIView alloc] initWithFrame:CGRectMake(0,0,100,100)];
[someOtherView addSubview:v];
[v centerHorizontally];
您的类别不正确。 不要牵扯到窗户。 您需要基于超级视图的大小:
- (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.