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

标签 iphone objective-c ios cocoa-touch

我正在尝试将我的 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/

相关文章:

iOS - 从 NSUserDefaults :Attempted to dereference an invalid ObjC Object or send it an unrecognized selector 获取 NSDictionary

iphone - 如何将UITabbar连接到ViewController

objective-c - NSLocale 的 NSLocaleCountryCode 键可以直接映射到 TLD 吗?

objective-c - 在 React Native 自定义 UI 组件中使用 CocoaPods 模块

objective-c - 如何从 NSBitmapImageRep 创建 CGImageRef?

ios - Swift - 集成 GameCenter 以使用排行榜

objective-c - iOS:警告:在演示过程中尝试在 <ViewController> 上呈现 <ModalViewController>

iphone - 如何在 iOS 4(3.1.3 更新)上使用 MPMoviePlayerController

iphone - CGContextDrawImage 返回错误的访问

ios - 如何避免 3rd 方框架之间的重复符号