gpt4 book ai didi

iphone - 为什么我的 UILabel 没有居中?

转载 作者:行者123 更新时间:2023-12-01 17:23:55 28 4
gpt4 key购买 nike

我正在尝试将我的 UILabel 水平居中。这就是它最终的样子(注意它没有中心)。

enter image description here

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

最佳答案

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

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

Now consider the same label contained within another view, where the outer [] represent the edges of the containing view, and the inner | represents the edges of the contained label. Notice how the inner label is not exactly centered within its superview, and is slightly pushed to the right (2 spaces away from the left, and 1 space closer to the right).

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

If you want the label to be center aligned within the superview or the screen at all times, you would want to make sure the width of the label matches its container, and then set textAlignment to center. Here's how:

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

This is a common case where you want the subview to match the exact size of the superview. You can use the bounds property to easily do that.

ReflectionView *aReflectionView = [[ReflectionView alloc] initWithFrame:..];
// Use the bounds of the superview to set the subview's frame.
UILabel *aLabel = [[UILabel alloc] initWithFrame:aReflectionView.bounds];

作为 UI 调试提示,尝试更改有问题的 View (标签)的背景以准确显示它所占用的区域,这通常有助于解决许多此类问题。

关于iphone - 为什么我的 UILabel 没有居中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10059577/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com