2

hi i'm begginer in objective-c and i want to learn how i can make UILabel in center of screen

this is my code:

XXRootViewController.h

@interface XXRootViewController : UIViewController{

UILabel *title; } @end

XXRootViewController.m

#import "XXRootViewController.h"

@implementation XXRootViewController {
NSMutableArray *_objects;
}

- (void)loadView {
[super loadView];

self.view = [[[UIView alloc]
    initWithFrame:[[UIScreen mainScreen] applicationFrame]]
autorelease];
self.view.backgroundColor = [UIColor whiteColor];

title = [[UILabel alloc] initWithFrame:CGRectMake(300,200,400,200)];
title.text = @"This is Sasuke's first app :)";
[self.view addSubview:title];
}

@end
aquan
  • 41
  • 4

3 Answers3

1

Try this code i make some changes in you code

self.view = [[UIView alloc]
                  initWithFrame:[UIScreen mainScreen].bounds];
self.view.backgroundColor = [UIColor whiteColor];

title = [[UILabel alloc] initWithFrame:CGRectMake(0,0,[UIScreen mainScreen].bounds.size.width - 50,200)];
title.text = @"This is Sasuke's first app :)";
title.textAlignment = NSTextAlignmentCenter;
title.center = self.view.center;
[self.view addSubview:title];
Hardik Thakkar
  • 15,269
  • 2
  • 94
  • 81
0

You just need to set frame in center of the screen ... change your one line code with it -

title = [[UILabel alloc] initWithFrame:CGRectMake(self.view.frame.size.width/2 - 200,self.view.frame.size.height/2 - 100,400,200)];

now your label is shown in the center of screen .. This will help you change the frame according to your use...

Abhishek Mishra
  • 1,625
  • 16
  • 32
0

Has Hardik Thakkar said, the best way would be to use the center method. That way, even if your label would grow, it will always be centred.

UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(300,200,400,200)];
label.text = @"something";
label.center = self.view.center; (this should always be you superview)

Now, even if your label is bigger than the size you were expecting, it will always be centred

Ricardo Alves
  • 642
  • 2
  • 13
  • 34