UILabel set to center of view
You need to init your view with a frame:
UIView *view = [[UIView alloc] initWithFrame:self.view.frame];
This is caused by your view
variable not having a frame defined. By default it has a frame set to (0, 0, 0, 0)
, so its center is (0, 0)
.
Hence when you do label.center = view.center;
, you set the center of your label to (0 - label.width / 2, 0 - label.height /2)
. (-80.5 -10.5; 161 21)
in your case.
There is no need for a new UIView
if your UIViewController
already have one, just work with 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;
}
Also note that doing label.center = self.view.center
will not work properly when rotating to landscape mode.