Skip to content

Instantly share code, notes, and snippets.

@rmenezes
Forked from SmartyP/ContentPageRenderer.cs
Created December 19, 2016 13:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rmenezes/62160ad5e774f55fff77fb0c061a4157 to your computer and use it in GitHub Desktop.
Save rmenezes/62160ad5e774f55fff77fb0c061a4157 to your computer and use it in GitHub Desktop.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
using Xamarin.Forms;
using Xamarin.Forms.Platform.iOS;
using UIKit;
using MyAppName.iOS.Renderers;
[assembly: ExportRenderer(typeof(ContentPage), typeof(ContentPageRenderer))]
namespace MyAppName.iOS.Renderers
{
/// <summary>
/// Custom renderer for ContentPage that allows for action buttons to be on the left or the right hand side (ex: a modal with cancel and done buttons)
/// ToolbarItems need to have Priority set to 0 to show on the left, 1 to show on the right (ref: https://gist.github.com/alexlau811/f1fff9e726333e6b4a2f)
/// </summary>
public class ContentPageRenderer : PageRenderer
{
public override void ViewWillAppear(bool animated)
{
base.ViewWillAppear(animated);
var contentPage = this.Element as ContentPage;
if (contentPage == null || NavigationController == null)
return;
var itemsInfo = contentPage.ToolbarItems;
var navigationItem = this.NavigationController.TopViewController.NavigationItem;
var leftNativeButtons = (navigationItem.LeftBarButtonItems ?? new UIBarButtonItem[] { }).ToList();
var rightNativeButtons = (navigationItem.RightBarButtonItems ?? new UIBarButtonItem[] { }).ToList();
var newLeftButtons = new UIBarButtonItem[] { }.ToList();
var newRightButtons = new UIBarButtonItem[] { }.ToList();
rightNativeButtons.ForEach(nativeItem =>
{
// [Hack] Get Xamarin private field "item"
var field = nativeItem.GetType().GetField("_item", BindingFlags.NonPublic | BindingFlags.Instance);
if (field == null)
return;
var info = field.GetValue(nativeItem) as ToolbarItem;
if (info == null)
return;
if (info.Priority == 0)
newLeftButtons.Add(nativeItem);
else
newRightButtons.Add(nativeItem);
});
leftNativeButtons.ForEach(nativeItem =>
{
newLeftButtons.Add(nativeItem);
});
navigationItem.RightBarButtonItems = newRightButtons.ToArray();
navigationItem.LeftBarButtonItems = newLeftButtons.ToArray();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment