2009-04-09 78 views
8

什么是中心在UIView标签的最佳方式居中标签?如果你做的事情如在一个UIView

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)]; 

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

回答

18

你做错了,主要就是采取起源值的一半,而不是尺寸的一半

但是,你并不需要,甚至计算出,在这种情况下 - 只是像做以下内容:


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),你可能也使用它的中心物业太:-)

6

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

childX = (parentWidth - childWidth)/2 

(这也适用于身高)。

+0

感谢安德鲁。你认为哪些是学习这些几何类型方程的最佳资源?简单的几何? – Coocoo4Cocoa 2009-04-10 00:20:17

+4

说实话,我不知道,像这样的东西只是基本的数学 - 你有一个你想分布在两边(/ 2)的一定数量的空间(parentWidth - childWidth)。 – 2009-04-10 00:31:09