为什么我的UILabel不居中?

Jon*_*Jon 1 iphone cocoa-touch objective-c ios

我试图将UILabel水平放置.这就是最终看起来像(注意它没有中心).

在此输入图像描述

    ReflectionView *aReflectionView = [[ReflectionView alloc]initWithFrame:CGRectMake(((self.view.bounds.size.width / 2) - 150), 40, 300, 90)];
    UILabel *aLabel = [[UILabel alloc]initWithFrame:CGRectMake(((self.view.bounds.size.width / 2) - 150), 0, 300, 90)];
    aLabel.textAlignment = UITextAlignmentCenter;
    aLabel.text = @"1 lbs";
    self.weightLabel = aLabel;
    [aReflectionView addSubview:self.weightLabel];
    self.weightReflectionView = aReflectionView;
    [self.view addSubview:self.weightReflectionView ];
    [self.weightReflectionView  updateReflection];
Run Code Online (Sandbox Code Playgroud)

Anu*_*rag 7

textAlignment属性将对齐文本框架内的文本UILabel,而不是文本框架内的文本.我的ASCII技能有点生疏,但这就是我的意思.考虑下面的标签,其中|指示标签的左/右边缘.

|173 lbs    | => left aligned
|    173 lbs| => right aligned
|  173 lbs  | => center aligned (not exactly centered in terms of its superview)

现在考虑另一个视图中包含的相同标签,其中outer []表示包含视图|的边缘,inner 表示包含的标签的边缘.注意内部标签在其超视图中是不是完全居中,并且稍微向右推(左边2个空格,右边靠近1个空格).

[  |173 lbs    | ] => left aligned
[  |    173 lbs| ] => right aligned
[  |  173 lbs  | ] => center aligned

如果您希望标签始终在超视图或屏幕中居中对齐,您可能需要确保标签的宽度与其容器匹配,然后设置textAlignment为居中.这是如何做:

[|173 lbs      |] => left aligned
[|      173 lbs|] => right aligned
[|   173 lbs   |] => center aligned (perfectly aligned)

这是您希望子视图与超级视图的确切大小匹配的常见情况.您可以使用该bounds属性轻松地执行此操作.

ReflectionView *aReflectionView = [[ReflectionView alloc] initWithFrame:..];
// Use the bounds of the superview to set the subview's frame.
UILabel *aLabel = [[UILabel alloc] initWithFrame:aReflectionView.bounds];
Run Code Online (Sandbox Code Playgroud)

作为一个UI调试技巧,尝试更改有问题的视图(标签)的背景,以准确显示它正在采取的区域,这通常有助于解决许多此类问题.