Separate title in NavigationBar and navigation but

2019-02-26 09:13发布

问题:

Hey, I have a stack of UIViewControllers inside of a UINavigationController. Usually the title (or the NavigationItem‘s title) decides about both the title that is displayed in the NavigationBar (displayed at the top) and all the navigation buttons, for example the back-buttons in the navigation bar itself.

Now I plan to put a bit more information into the NavigationBar‘s title, while still keeping those button labels short and concise (for example the view‘s title is “<Customer name> Overview”, while the buttons should just show “Overview”).

I am currently trying to achieve this by changing the NavigationItem‘s title on ViewWillAppear and ViewWillDisappear. This works well, but one can see the moments where the text changes (probably due to the animation). I‘ve tried different combinations with ViewDidAppear and ViewDidDisappear as well, but the effect was the best with just the Will methods. An example code for this is shown below (the Example class is pushed to a UINavigationController).

Is there a better way to achive this? Maybe with simply changing the button titles only or with just directly changing the navigation‘s title? Or can I maybe prevent the standard mechanisms from copying the title to all other instances?

public class Example : UIViewController
{
    private int depth;

    public Example ( int depth = 0 )
    {
        this.depth = depth;
        this.Title = "Title";
    }

    public override void ViewDidLoad ()
    {
        base.ViewDidLoad();

        UIButton btn = new UIButton( new RectangleF( 100, 100, 300, 50 ) );
        btn.SetTitle( "Duplicate me!", UIControlState.Normal );
        btn.TouchDown += delegate(object sender, EventArgs e) {
            NavigationController.PushViewController( new Example( depth + 1 ), true );
        };
        View.Add( btn );
    }

    public override void ViewWillAppear ( bool animated )
    {
        base.ViewWillAppear( animated );
        this.NavigationItem.Title = String.Format( "Title / {0}", depth );
    }

    public override void ViewWillDisappear ( bool animated )
    {
        base.ViewWillDisappear( animated );
        this.NavigationItem.Title = "Title";
    }
}

回答1:

If I understand you correctly, I think there's a ready-made for this:

Set backBarButtonItem on your view controller's navigation item.