0

In Xamarin Forms I'm trying to left align the page title, I know I need a custom renderer but I'm not sure where to go after the following code.

This might not even be correct, but I think I need to create a page renderer and do the alignment there?

[assembly: ExportRenderer(typeof(Page), typeof(gl_mobile_app.iOS.TitleExRenderer))]
namespace gl_mobile_app.iOS
{
    public class TitleExRenderer : Xamarin.Forms.Platform.iOS.PageRenderer
    {
        protected override void OnElementChanged(VisualElementChangedEventArgs e)
        {
            base.OnElementChanged(e);
            // align title
        }
    }
}
DarkW1nter
  • 2,933
  • 11
  • 67
  • 120

1 Answers1

1

This is not officially supported by apple in the default UINavigationBar.

You can try a trick: put a label in the TopItem.LeftBarButtonItem and dont use the default Title property

Something like this in your custom renderer:

var label = new UILabel();
//this is the variable containing the title you need to pass it as a bindable property
label.Text = title; 
label.TextAlignment = UITextAlignment.Left;
label.SizeToFit();
NavigationController.NavigationBar.TopItem.LeftBarButtonItem = new UIBarButtonItem(label);

Update

You can also give a read to this excellent blog post: http://www.xamboy.com/2017/12/06/navigation-bar-customization-in-xamarin-forms/

Update 2

You can try to grab the default page title, use it in your left position and then dispose it, something like this:

var label = new UILabel();
//get the default title
label.Text =  NavigationController.NavigationBar.TopItem.Title; 
label.TextAlignment = UITextAlignment.Left;
label.SizeToFit();

//empty the default title (try with empty string or null if empty doesnt work)
NavigationController.NavigationBar.TopItem.Title = "";    

NavigationController.NavigationBar.TopItem.LeftBarButtonItem = new UIBarButtonItem(label);

This is untested, let me know if it works out :)

GiampaoloGabba
  • 1,428
  • 1
  • 15
  • 21
  • Hi, thanks for this, I have it working if I hard code the title, but is there a way I can use the actual page title its self, while setting the page title to null? I can't seem to access the title in the renderer (doing it wrong obviously) – DarkW1nter Jun 27 '18 at 09:05
  • 1
    I updated the answer with a trick to get the default page title and use it in the left position – GiampaoloGabba Jun 27 '18 at 09:44
  • Thanks again, I had tried that but my problem was I set the title in OnAppearing (from database data), the renderer runs before OnAppearing so just had to set the title in the constructor and it's all good – DarkW1nter Jun 27 '18 at 09:54