Xamarin表单TabbedPage选项卡未选择的颜色

时间:2016-11-06 14:23:13

标签: c# xamarin xamarin.ios xamarin.forms

我正在尝试从TabbedPage更改未选中的图标的颜色。

enter image description here

我有一个自定义TabbedRenderer:

public class CustomTabbedPage : TabbedRenderer
{
    public override void ViewWillAppear(bool animated)
    {
        if (TabBar == null) return;
        if (TabBar.Items == null) return;

        var tabs = Element as TabbedPage;
        if (tabs != null)
        {
            for (int i = 0; i < TabBar.Items.Length; i++)
            {
                UpdateItem(TabBar.Items[i], tabs.Children[i].Icon);
            }
        }

        base.ViewWillAppear(animated);
    }

    private void UpdateItem(UITabBarItem item, string icon)
    {
        if (item == null)
            return;
        try
        {
            icon = icon.Replace(".png", " Filled.png");
            if (item == null) return;
            if (item.SelectedImage == null) return;
            if (item.SelectedImage.AccessibilityIdentifier == icon) return;
            item.SelectedImage = UIImage.FromBundle(icon);
            item.SelectedImage.AccessibilityIdentifier = icon;
        }
        catch (Exception ex)
        {
            Console.WriteLine("Unable to set selected icon: " + ex);
        }
    }
}

我设法更改了所选的项目文字颜色和未选择的项目文字颜色,但没有更改图标颜色。

谢谢!

3 个答案:

答案 0 :(得分:2)

未选择的图标颜色: 在最开始或您的ViewWillAppear事件中添加一行:

        TabBar.UnselectedItemTintColor = UIColor.Red; //red is for the yay effect :)

答案 1 :(得分:1)

private void UpdateItem(UITabBarItem item, string icon)
{
    if (item == null)
         return;
    try
    {
         string newIcon = icon.Replace(".png", " Filled.png");
         if (item == null) return;
         if (item.SelectedImage == null) return;
         if (item.SelectedImage.AccessibilityIdentifier == icon) return;

         item.Image = UIImage.FromBundle(icon);
         item.Image = item.Image.ImageWithRenderingMode(UIKit.UIImageRenderingMode.AlwaysOriginal);

         item.SelectedImage = UIImage.FromBundle(newIcon);
         item.SelectedImage = item.SelectedImage.ImageWithRenderingMode(UIKit.UIImageRenderingMode.AlwaysOriginal);

         item.SelectedImage.AccessibilityIdentifier = icon;
     }
     catch (Exception ex)
     {
         Console.WriteLine("Unable to set selected icon: " + ex);
     }
}

答案 2 :(得分:1)

Xamarin Forms 4+现在在 TabbedPage 对象上具有 SelectedTabColor UnselectedTabColor 属性,可以轻松地直接从共享代码中进行设置,这会影响文字和图标(但是选择后换成其他图像当然仍然需要自定义渲染器)。