1

I am trying to set the title of my navigation item by setting a UILabel to it. The code essentially works, but my is problem that when the View loads, for a second or so the UILabel starts at the position defined by the CGRectMake rather that at the top and middle of the navigation bar where it belongs. Is there a way to default having the UILabel start in the correct position?

The obvious work around is to set the initial position off the screen so it is hidden and then after a split second the UILabel moves to the correct place. but this seems to be the 'wrong' way to accomplish what I need. below is the code.

@property (nonatomic, strong) UILabel *titleView;

...

self.titleView = [[UILabel alloc] initWithFrame:CGRectMake(20.0f, 0.0f, 150.0f, 128.0f)];
self.titleView.font = [UIFont systemFontOfSize:10.0f];
self.titleView.text = @"My title";
self.navigationItem.titleView = self.titleView;

3 Answers3

0

Default alignment of text in UILabel is set to left, so you need to make it center programatically.

Try this,

self.titleView = [[UILabel alloc] initWithFrame:CGRectMake(20.0f, 0.0f, 150.0f, 128.0f)];
self.titleView.font = [UIFont systemFontOfSize:10.0f];
self.titleView.text = @"My title";
[self.titleView setTextAlignment:NSTextAlignmentCenter]; //ADD THIS
self.navigationItem.titleView = self.titleView;
βhargavḯ
  • 9,786
  • 1
  • 37
  • 59
  • Hi, thanks for the answer. My problem is not that the text is misaligned, but rather that the entire label is misplaced. – user2970395 Nov 14 '13 at 17:13
0

Try this

self.titleView = [[UILabel alloc] initWithFrame:CGRectMake(0.0f, 0.0f, 150.0f,44.0f)];
[self.titleView setTextAlignment:UITextAlignmentCenter]; 
Ravindhiran
  • 5,304
  • 9
  • 50
  • 82
0

I have solved my problem like this way

UILabel * label = [[[UILabel alloc] initWithFrame:CGRectMake(0,0,45,45)] autorelease];
label.textColor = [UIColor whiteColor];
label.backgroundColor = [UIColor clearColor];
label.font = [UIFont boldSystemFontOfSize:20];
self.navigationItem.titleView = label;
label.text = @"Customer"; //CUSTOM TITLE
[label sizeToFit];
Retro
  • 3,985
  • 2
  • 17
  • 41