开发者

another way for adding a title to a uinavbar programmatically?

开发者 https://www.devze.com 2023-03-21 04:11 出处:网络
I am trying to add a title to my nav bar which I have added programmatically. I know i can create a label and add it as a subview, but then I need to add tons of configurations for it to be placed cor

I am trying to add a title to my nav bar which I have added programmatically. I know i can create a label and add it as a subview, but then I need to add tons of configurations for it to be placed correctly like in a typical nav开发者_开发技巧 bar title. Is there any other way to do that than this:

- (void)viewDidLoad
{
[super viewDidLoad];

//Adding navBar programmatically 
CGFloat width = self.view.frame.size.width;
UINavigationBar *navBar = [[UINavigationBar alloc] initWithFrame:CGRectMake(0,0,width,52)];
navBar.autoresizingMask = UIViewAutoresizingFlexibleWidth;

//Adding title programmatically 
UILabel *lblTitle  = [[UILabel alloc]initWithFrame:CGRectMake(10,10,80,30)];
lblTitle.text = @"Title";
[navBar addSubview: lblTitle];

[self.view addSubview:navBar];

}

And if not (sorry for another question, just think it relates) how do I set up my lblTitle to look like a normal nav bar title that you will find in most of the apps.

Thanks!


If you are adding the navigation bar by programmatically means, use this

 (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"yourTitle";
}

You can also use

self.navigationItem.title = @"yourTitle";


You can use

navigationBar.topItem.title = @"Your Title";


The best answer to your question is just to use a UINavigationController to get its navigation bar for free, but if for some reason you can’t do that, you’ll need to use a custom UILabel and play with its properties until you match the style of the built-in one.


If a simple UILabel does not satisfy you, then yes, you need tons of configuration or you can do that in Interface Builder to polish your view. Instead of adding it as a subview, I suggest that you set it as navigationItem.titleView in your -(void)viewDidLoad.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号