【发布时间】: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