【问题标题】:Centering a label in a UIView在 UIView 中将标签居中
【发布时间】:2010-10-18 16:31:12
【问题描述】:

UIView 中将标签居中的最佳方法是什么?如果您执行诸如

之类的操作
UILabel *myLabel = [[UILabel alloc] initWithFrame:CGRectMake(view.frame.origin.x / 2, view.frame.origin.y / 2, 50.0, 50.0)];

然后您将标签的原点设置为视图的中心。最好的办法是使用 center 属性将视图的中心设置为该点。所以我尝试使用以下代码:

UIView *aView = [[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease];
aView.backgroundColor = [UIColor darkGrayColor];
CGRect frame = aView.frame;

UILabel *aLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 125.0f, 30.0f)];
[aLabel setCenter:CGPointMake(frame.origin.x / 2, frame.origin.y / 2)];

这会产生一个标签,该标签几乎超出了左上角的视图范围。

【问题讨论】:

    标签: ios objective-c iphone cocoa-touch uilabel


    【解决方案1】:

    你做错的主要事情是取一半 origin 值,而不是一半 sizes

    但是,在这种情况下,您甚至不需要计算 - 只需执行以下操作:

    
    UIView *aView = [[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease];
    aView.backgroundColor = [UIColor darkGrayColor];
    
    UILabel *aLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 125, 30)];
    aLabel.center = aView.center;
    

    (注意,您不需要将这些坐标强制为浮点数 - 在这种情况下,将它们写成整数似乎更易读)。

    另外,这是一个风格问题 - 但由于您已经在使用属性语法 (aView.backgroundColor),您也可以将它用于 center 属性:-)

    【讨论】:

      【解决方案2】:

      要在父级中水平居中定位任何子级,您可以这样计算其位置;

      childX = (parentWidth - childWidth) / 2
      

      (这也适用于高度)。

      【讨论】:

      • 谢谢安德鲁。您认为学习这些几何类型方程的最佳资源在哪里?简单几何?
      • 老实说我不知道​​,这样的事情只是基本的数学 - 你有一定数量的空间(parentWidth - childWidth),你想在两侧分配(/ 2)。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-05-07
      • 2020-12-30
      • 2011-07-04
      • 2019-01-31
      相关资源
      最近更新 更多