Ios 在视图中使标签居中
在Ios 在视图中使标签居中,ios,objective-c,iphone,cocoa-touch,uilabel,Ios,Objective C,Iphone,Cocoa Touch,Uilabel,在ui视图中居中放置标签的最佳方法是什么?如果你做了一些事情,比如 UILabel *myLabel = [[UILabel alloc] initWithFrame:CGRectMake(view.frame.origin.x / 2, view.frame.origin.y / 2, 50.0, 50.0)]; 然后将标签的原点设置为视图的中心。最好是使用“中心”特性将视图的中心设置为该点。因此,我尝试使用以下代码: UIView *aView = [[[UIView alloc] ini
ui视图中居中放置标签的最佳方法是什么?如果你做了一些事情,比如
UILabel *myLabel = [[UILabel alloc] initWithFrame:CGRectMake(view.frame.origin.x / 2, view.frame.origin.y / 2, 50.0, 50.0)];
然后将标签的原点设置为视图的中心。最好是使用“中心”特性将视图的中心设置为该点。因此,我尝试使用以下代码:
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)];
这会产生一个标签,该标签几乎超出左上角视图的边界。要将任何子对象水平居中放置在父对象中,您可以这样计算其位置
childX = (parentWidth - childWidth) / 2
(这也适用于高度)。您犯的主要错误是取了原点值的一半,而不是尺寸的一半
但是,在这种情况下,您甚至不需要计算,只需执行以下操作:
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;
(注意,您不需要强制将这些坐标设为浮点数——在本例中,将它们写成int似乎更具可读性)
此外,这是一个风格问题-但是既然您已经在使用属性语法(aView.backgroundColor
),那么您也可以将其用于中心属性:-)谢谢Andrew。你认为哪里是学习这些几何型方程的最佳资源?简单的几何?老实说,我不知道,像这样的东西只是基本的数学-你有一个设定的空间量(parentWidth-childWidth),你想分布在两边(/2)。