在UIView中居中标签 [英] Centering a label in a UIView

查看:1023
本文介绍了在UIView中居中标签的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

UIView 中将标签居中的最佳方法是什么?如果你做了

What's the best way to center a label in a UIView? If you do something such as

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

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

Then you're setting the origin point of the label to the center of the view. The best bet would be to set the center of the view to that point using the center property. So I tried using the following code:

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

这产生的标签几乎超出了左上角视图的边界。

That yields a label which is pretty much outside the bounds of the view in the upper left hand corner.

推荐答案

你做错了的主要原因是使用了 origin 值的一半,

The main thing you are doing wrong is taking half the origin values, rather than half the sizes

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

However, you don't need to even calculate that in this case - just do something like the following:


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

(note, you don't need to force those coordinates to floats - in this case writing them as ints seems more readable).

此外,这是一个风格问题 - 但是由于你已经使用了属性语法( aView.backgroundColor )你也可以使用它的中心属性太: - )

Also, it's a matter of style - but since you're already using property syntax (aView.backgroundColor) you may as well use it for the center property too :-)

这篇关于在UIView中居中标签的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆