将标签置于UIView中
在UIView
居中放置标签的最好方法是什么? 如果你做了这样的事情
UILabel *myLabel = [[UILabel alloc] initWithFrame:CGRectMake(view.frame.origin.x / 2, view.frame.origin.y / 2, 50.0, 50.0)];
然后,您将标签的原点设置到视图的中心。 最好的select是使用中心属性将视图的中心设置为该点。 所以我尝试使用下面的代码:
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)];
这产生了一个标签,在左上angular的视图范围之外。
你做错的主要事情是取原始值的一半,而不是一半的大小
但是,在这种情况下,您甚至不需要计算 – 只需执行以下操作:
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
),你也可以使用它的中心属性:-)
要定位任何一个水平居中在父母中的孩子,你可以这样计算其位置;
childX = (parentWidth - childWidth) / 2
(这也适用于高度)。