【问题标题】:UILabel set to center of viewUILabel 设置为视图中心
【发布时间】:2013-06-05 20:57:51
【问题描述】:

这段代码中绘制的UILabel怎么不在view的中心?

//create the view and make it gray
UIView *view = [[UIView alloc] init];
view.backgroundColor = [UIColor darkGrayColor];

//everything for label
UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0,0,42,21)];

//set text of label
NSString *welcomeMessage = [@"Welcome, " stringByAppendingString:@"username"];
welcomeMessage = [welcomeMessage stringByAppendingString:@"!"];
label.text = welcomeMessage;

//set color
label.backgroundColor = [UIColor darkGrayColor];
label.textColor = [UIColor whiteColor];

//properties
label.textAlignment = NSTextAlignmentCenter;
[label sizeToFit];

//add the components to the view
[view addSubview: label];
label.center = view.center;

//show the view
self.view = view;

label.center = view.center; 这一行应该将label 移动到view 的中心。而是将其移动到label 的中心位于view 左下角的位置,如下所示。


(来源:gyazo.com

有人知道为什么吗?

【问题讨论】:

  • 首先你为什么要self.view=view?你不需要那个,其次你的view 没有框架集。三、使用 label.center = self.view.center.
  • 首先,因为我正在应用程序中构建视图。其次,我该怎么做。第三,我使用view.center,因为我正在创建一个新视图。我需要使用self.view= view将视图设置为UIView *view
  • 我想这段代码在-viewDidLoad。对吗?
  • 第二,视图的alloc/init,view.frame = CGRectMake(...)
  • 是的,这就是为什么我也在你的上一个问题中解释过。如果没有提供框架,则视图具有 CGRectZero 框架,即 (0,0,0,0)。所以总是为 UIViews 设置一个框架。

标签: ios objective-c uiview uilabel


【解决方案1】:

你需要用一个框架来初始化你的视图:

UIView *view = [[UIView alloc] initWithFrame:self.view.frame];

【讨论】:

    【解决方案2】:

    这是由您的 view 变量未定义框架引起的。默认情况下,它的框架设置为(0, 0, 0, 0),因此它的中心是(0, 0)

    因此,当您执行label.center = view.center; 时,您将标签的中心设置为(0 - label.width / 2, 0 - label.height /2)(-80.5 -10.5; 161 21) 在你的情况下。

    如果您的UIViewController 已经有了一个新的UIView,则无需使用self.view

    - (void)viewDidLoad
    {
        [super viewDidLoad];
    
        //create the view and make it gray
        self.view.backgroundColor = [UIColor darkGrayColor];
    
        //everything for label
        UILabel *label = [[UILabel alloc] init];
    
        //set text of label
        // stringWithFormat is useful in this case ;)
        NSString *welcomeMessage = [NSString stringWithFormat:@"Welcome, %@!", @"username"];
        label.text = welcomeMessage;
    
        //set color
        label.backgroundColor = [UIColor darkGrayColor];
        label.textColor = [UIColor whiteColor];
    
        //properties
        label.textAlignment = NSTextAlignmentCenter;
        [label sizeToFit];
    
        //add the components to the view
        [self.view addSubview: label];
        label.center = self.view.center;
    }
    

    还要注意label.center = self.view.centerwill not work properly when rotating to landscape mode

    【讨论】:

      【解决方案3】:

      如果您将代码放在 viewDiLayoutSubviews 而不是 viewDidLoad 中,您的代码会正常工作

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-01-26
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多