简体   繁体   English

如何正确设置UIViewController的navigationController标题?

[英]How do I correctly set a UIViewController's navigationController title?

I am trying the following code: 我正在尝试以下代码:

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
 Thing *sub = [[subscriptions objectAtIndex:indexPath.row] retain];
 StoriesViewController *thing = [[StoriesViewController alloc] initWithThing:sub];
 thing.navigationController.title = sub.title;
 [self.navigationController pushViewController:thing animated:YES];
 [thing release];
 [sub release];

 [tableView deselectRowAtIndexPath:indexPath animated:YES];
}

I thought this is how you correctly set the title for pushing the controller. 我认为这是您正确设置用于推动控制器的标题的方式。 I tried thing.title however that was setting the TabBarItem's title instead. 我尝试了thing.title,但是设置了TabBarItem的标题。

thing.navigationItem.title = sub.title;

或在viewDidLoad方法的StoriesViewController.m文件中:

self.navigationItem.title = sub.title

It's possible you're pushing a UITabBarController instead of your regular view controller. 您可能正在推送UITabBarController而不是常规视图控制器。 In this case, the navigationItem will display the title of the current controller, the tab bar controller, even though you see another view. 在这种情况下,即使您看到另一个视图,navigationItem也会显示当前控制器的标题,即标签栏控制器。 You would have to change the tab bar controller's title to change the text displayed above. 您必须更改标签栏控制器的标题才能更改上面显示的文本。

self.tabBarController.title = @"Your title";

The title needs to be set in (or after) viewDidLoad , so if you want to set from another class that is creating StoriesViewController. 标题需要在viewDidLoad中(或之后)设置,因此如果要从另一个正在创建StoriesViewController的类中进行设置。

  1. Make another property and have that class set it. 设置另一个属性,并设置该类。
  2. In StoriesViewController's viewDidLoad , set the title from that property. 在StoriesViewController的viewDidLoad ,从该属性设置标题。

This is because outlets aren't initialized to their view counterparts until viewDidLoad . 这是因为直到viewDidLoad出口都没有初始化为其视图副本。

It looks like StoriesViewController is holding on to sub (does the initWithThing set a property to it?) If so, just set the title in viewDidLoad to the Thing property's title. 看起来StoriesViewController坚持使用sub(initWithThing是否为其设置了属性?)如果是这样,只需将viewDidLoad中的标题设置为Thing属性的标题即可。

[thing setTitle: sub.title];

The solution was thing.navigationItem.title = @"title"; 解决的办法是thing.navigationItem.title = @"title"; however it turns out that subclassing a UINavigationController broke it somehow and my solution to that was to use a category rather than a subclass 但是事实证明,子类化UINavigationController会以某种方式破坏它,而我的解决方案是使用类别而不是子类

如果您的UIViewControllerUITabController一部分,则可以执行以下操作:

self.tabBarController.title = sub.title;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM