6

为什么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

有谁知道为什么?

4

3 回答 3

5

您需要使用框架初始化视图:

UIView *view = [[UIView alloc] initWithFrame:self.view.frame];
于 2013-06-05T21:13:51.637 回答
4

这是由于您的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)在你的情况下。

UIView如果您已经拥有一个,则不需要新的UIViewController,只需使用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.center 当旋转到横向模式时,doing 将无法正常工作

于 2013-06-05T21:09:31.970 回答
0

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

于 2015-09-22T19:01:56.293 回答