Xamarin.Forms: Add content to TitleView in your iOS app

If you’re building an iOS app you maybe want to add content to the NavigationBar. This blog post will show you how to build a generic solution so you don’t have to write a custom renderer for each view that you want NavigationBar content for.

First of all I creating a new class that inherits from ContentPage and adding a property of type View. I use to name the property TitleView, because that’s the name in iOS.

public class ExtendedContentPage : Xamarin.Forms.ContentPage
{
    public View TitleView { get; set; }
}

Now If your views/pages inherits from your new class you can add content to TitleView.

<local:ExtendedContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:local="clr-namespace:TitleViewSample"
             x:Class="TitleViewSample.MainView">
  <local:ExtendedContentPage.TitleView>
    <Button x:Name="TestButton" Text="Test" BackgroundColor="Green" />
  </local:ExtendedContentPage.TitleView>
</local:ExtendedContentPage>

To get it work you also have to write a custom page renderer for iOS. Override the WillMoveToParentViewController method in the renderer that will inherit PageRenderer and add the code below.

 base.WillMoveToParentViewController(parent);
 
 var page = (ExtendedContentPage)Element;
 
 var renderer = RendererFactory.GetRenderer(page.TitleView);
 var view = renderer.NativeView;
 view.SizeToFit();
 
 parent.NavigationItem.TitleView = view.Subviews[0];

It is important that you adding the first subview of the native view, otherwise it will be just blank.

The complete code can be found on GitHub, https://github.com/dhindrik/XamarinFormsSamples/tree/master/TitleView

8 thoughts on “Xamarin.Forms: Add content to TitleView in your iOS app

  1. Brew says:

    Hi Daniel,

    I tried to change the button control to just the label control and it did not show up. Does this approach only work with the button control?

    Brew

  2. Peter Conrey says:

    Although StackLayout is a view, I’ve tried it and it doesn’t appear to work. I have one with a label and an image, and nothing shows up. Any suggestions?

Leave a Reply

Your email address will not be published. Required fields are marked *