【问题标题】:Trying to center a view within its superview试图在其超级视图中居中视图
【发布时间】:2016-09-11 16:56:39
【问题描述】:

我正在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];

但是,这似乎不起作用。我的解决方案有什么不正确的地方?

【问题讨论】:

  • @SathiReddy - 请通过添加一个不必要的标签来停止不必要的编辑问题。编辑应该有用且完整。不要只是添加标签。修复问题中可能出现的所有问题。或者在这种情况下,不要做任何事情。您的大部分标签编辑建议都是不必要的。

标签: ios objective-c uiview


【解决方案1】:

您需要先将视图添加到父视图,然后才能将其居中。

UIView *v = [[UIView alloc] initWithFrame:CGRectMake(0,0,100,100)];
[someOtherView addSubview:v];
[v centerHorizontally];

而且您的类别不正确。不要涉及窗口。您需要根据 superview 的大小来确定它:

- (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));
}

【讨论】:

  • 我想你的意思是 bounds.size.widthbounds.size.height 但谢谢!
  • 是的,已修复。谢谢。
猜你喜欢
  • 2015-11-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-11-24
  • 2020-11-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多