UILabel设置为视图中心

Dum*_*ode 5 objective-c uiview uilabel ios

为什么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;
Run Code Online (Sandbox Code Playgroud)

该线,label.center = view.center;应该移动label到中心view.但是将其移动到label位于左下角的中心位置,view如下所示.

截图http://gyazo.com/2d1c064a671e32c7eb004647232fa430.png

有谁知道为什么?

Cor*_*rey 5

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

UIView *view = [[UIView alloc] initWithFrame:self.view.frame];
Run Code Online (Sandbox Code Playgroud)