I am trying to add two labels – one on the left and one on the right of a UINavigationBar in my UIViewController implementation programmatically. However It doesn’t show up when I run my program. I have a UIViewController that is embedded in a UINavigationController. I am using following code:
- (void) setTheNavigationbarView{
CGFloat originX = self.navigationItem.titleView.bounds.origin.x;
CGFloat originY = self.navigationItem.titleView.bounds.origin.y;
CGFloat sizeW = self.navigationItem.titleView.bounds.size.width;
CGFloat sizeH = self.navigationItem.titleView.bounds.size.height;
UIView * navigationbarView = [[UIView alloc] initWithFrame:CGRectMake(originX + 1, originY + 1, sizeW - 2, sizeH - 2)];
navigationbarView.backgroundColor = [UIColor clearColor];
UILabel *labelLeft = [[[UILabel alloc] initWithFrame:CGRectMake(0, 0, (sizeW - 2)/2, (sizeH - 2))] autorelease];
labelLeft.backgroundColor = [UIColor clearColor];
labelLeft.font = [UIFont boldSystemFontOfSize:16];
labelLeft.adjustsFontSizeToFitWidth = NO;
labelLeft.textAlignment = UITextAlignmentLeft;
labelLeft.textColor = [UIColor blackColor];
labelLeft.text = @"first line";
labelLeft.highlightedTextColor = [UIColor blackColor];
[navigationbarView addSubview:labelLeft];
UILabel *labelRight = [[[UILabel alloc] initWithFrame:CGRectMake(((sizeW - 2)/2 + 1), 0, (sizeW - 2)/2, (sizeH - 2))] autorelease];
labelRight.backgroundColor = [UIColor clearColor];
labelRight.font = [UIFont boldSystemFontOfSize:16];
labelRight.adjustsFontSizeToFitWidth = NO;
labelRight.textAlignment = UITextAlignmentRight;
labelRight.textColor = [UIColor blackColor];
labelRight.text = @"second line";
labelRight.highlightedTextColor = [UIColor blackColor];
[navigationbarView addSubview:labelRight];
// set the view as navigationba title view
self.navigationItem.titleView = navigationbarView;
}
I will appreciate any help. Thanks.
I test your code and its work for me, i would only check if your frame is not bigger than every size of your navigaitonController.