【问题标题】:How to center any subview horizontally in parent UIView but not vertically?如何在父 UIView 中水平居中任何子视图但不垂直居中?
【发布时间】:2015-07-06 04:48:10
【问题描述】:

如何将其父 UIview 中的任何子视图仅水平居中,而不是垂直居中。我尝试了child.center = parent.center,但它将我的子视图水平和垂直放置在父视图的中心。我怎样才能将它水平对齐在中心。谢谢

【问题讨论】:

  • 只设置center.x,忽略y值
  • center 是一个 CGPoint。你应该能够将它的 x 值设置为父视图中心 x 值

标签: ios objective-c


【解决方案1】:

像这样只改变中心可能会有所帮助

child.center = CGPointMake(CGRectGetMidX(parentView.bounds), child.center.y);

【讨论】:

  • 请您告诉我child.center.y和child.origin.y之间有什么区别。
  • @ChrisH 是的,我在答案中犯了一个错误。感谢您指出。
  • @Zeebok center 告诉它在它的超级视图坐标系中的中心点,而原点告诉它在它的超级视图坐标系中的视图位置。有关详细说明,请查看此stackoverflow 问题。
  • @Jaideep np - 你也可以更进一步,使用parent.center.x 作为第一个值。
【解决方案2】:

您不能直接修改UIViewControllercenterx属性,但可以执行以下操作:

CGPoint center = child.center;
center.x = parent.center.x;
child.center = center;

【讨论】:

  • 非常感谢 Jaideep,您的回答非常棒。您的答案很容易理解,但我有点困惑。 Jaideep 也给出了一个很好的答案,我很困惑我应该接受哪一个。你们俩都很棒。
【解决方案3】:

试试这个,

subview.frame = CGRectMake(((parentView.frame.size.width/2)-(subview.frame.size.width/2)),subview.frame.origin.y,subview.frame.size.width,subview.frame.size.height);

【讨论】:

    【解决方案4】:

    我需要为每个不同的设备尺寸水平居中(但不是垂直)一个 UIImageView,所以我使用了这个,效果很好:

    CGRect screenRect = [[UIScreen mainScreen] bounds];
    [self.myImageView setCenter:CGPointMake(CGRectGetMidX(screenRect), self.myImageView.frame.origin.y + self.myImageView.frame.size.height/2)];
    

    【讨论】:

      猜你喜欢
      • 2014-09-17
      • 1970-01-01
      • 2017-08-24
      • 2014-03-16
      • 2012-09-23
      • 2016-07-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多