UILabel设置为视图中心

时间:2013-06-05 20:57:51

标签: ios objective-c uiview uilabel

为什么此代码中绘制的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左侧的位置,如下所示。

screenshot http://gyazo.com/2d1c064a671e32c7eb004647232fa430.png

有谁知道为什么?

3 个答案:

答案 0 :(得分: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

另请注意,执行{{1}} will not work properly when rotating to landscape mode

答案 1 :(得分:4)

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

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

答案 2 :(得分:0)

如果将代码放在viewDiLayoutSubviews中而不是viewDidLoad

,您的代码将正常工作