如何在Xamarin.Forms中将ToolbarItem设置为左侧?

时间:2017-07-18 06:25:43

标签: xamarin.forms

我想在导航栏的左侧设置一个ToolbarItem,但我不知道如何设置它。 Xamarin.Forms的默认ToolbarItem位于右侧

1 个答案:

答案 0 :(得分:0)

在iOS中,我使用自定义渲染器,我不认为有任何解决方法。在Android中,我并不感到烦恼,因为人们已经习惯了右侧的物品。下面的渲染器检查是否有超过1个ToolBarItems,如果是,则将其移到左侧。

[assembly: ExportRenderer(typeof(ContentPage), typeof(LeftNavigationItemRenderer))]
namespace MyApp.iOS
{
    public class LeftNavigationItemRenderer : PageRenderer
    {
        public override void ViewWillAppear(bool animated)
        {
            base.ViewWillAppear(animated);

            if (NavigationController == null)
                return;

            var navigationItem = NavigationController.TopViewController.NavigationItem;
            var leftNativeButtons = (navigationItem.LeftBarButtonItems ?? new UIBarButtonItem[] { }).ToList();
            var rightNativeButtons = (navigationItem.RightBarButtonItems ?? new UIBarButtonItem[] { }).ToList();

            if (rightNativeButtons.Count > 1)
            {
                var nativeItem = rightNativeButtons.Last();
                rightNativeButtons.Remove(nativeItem);
                leftNativeButtons.Add(nativeItem);
            }

            navigationItem.RightBarButtonItems = rightNativeButtons.ToArray();
            navigationItem.LeftBarButtonItems = leftNativeButtons.ToArray();
        }
    }
}