UIViewController Title attribute in Storyboard

后端 未结 10 2111
南旧
南旧 2021-02-03 19:58

I am setting the title field of a UIViewController via Interface Builder/Storyboard: \"enter

10条回答
  •  隐瞒了意图╮
    2021-02-03 20:27

    I ran into this issue this morning. Here are the stabs I took and the final workaround.

    This correctly logs the child view controller's title as set in the storyboard, but has no effect on what's being presented:

    - (void)viewDidLoad
    {
        [super viewDidLoad];
    
        NSLog(@"Title: %@", self.title);
    }
    

    This has no effect; the title still doesn't show (probably doing an "if (![_title isEqualToString:title]){}" user the hood:

    - (void)viewDidLoad
    {
        [super viewDidLoad];
        self.title = [self.title copy];
    }
    

    This causes the title to be set correctly:

    - (void)viewDidLoad
    {
        [super viewDidLoad];
        NSString *title = self.title;
        self.title = nil;
        self.title = title;
    }
    

    My guess is that the UINavigationController is pulling the title for the view being presented before it has been loaded from the storyboard, but then doesn't start listening for changes until after the property has been set. I don't use storyboards or nibs very often, however, so it's quite possible there's a magic checkbox for this hidden somewhere that I've missed.

    In any case, it looks like you can either do the self.navigationItem.title = self.title dance, or the above, as a workaround and still maintain your titles in IB.

    Apples docs for this are kinda clear:

    The navigation controller updates the middle of the navigation bar as follows:

    • If the new top-level view controller has a custom title view, the navigation bar displays that view in place of the default title view. To specify a custom title view, set the titleView property of the view controller’s navigation item.

    • If no custom title view is set, the navigation bar displays a label containing the view controller’s default title. The string for this label is usually obtained from the title property of the view controller itself. If you want to display a different title than the one associated with the view controller, set the title property of the view controller’s navigation item instead.

    Emphasis mine.

提交回复
热议问题