【问题标题】:Xamarin iOS ToolbarItem Image showing white imageXamarin iOS ToolbarItem 图像显示白色图像
【发布时间】:2021-10-06 15:20:08
【问题描述】:

Xamarin Forms IconImageSource:

在 Android 工具栏上正确显示图像,在 iOS 上显示白色图像。我怎样才能解决这个问题? 我将文件添加到资源文件夹并将构建操作设置为 BundleResource。

如果我将文件名更改为非现有文件,则根本不显示图像。我尝试将扩展名更改为 JPG,结果相同,还显示了白色图像。

我使用了这个代码片段。

        ToolbarItem toolbarItemSearch = new ToolbarItem { IconImageSource = ImageSource.FromFile("searchIcon.png") };
        ToolbarItems.Add(toolbarItemSearch);

【问题讨论】:

    标签: xamarin


    【解决方案1】:

    iOS默认为ToolbarItems着色,颜色为蓝/白。

    为了解决这个问题,我们需要为 NavigationPage 创建一个自定义渲染器,并将 TintColor 设置为透明,并将图像设置为另一种渲染模式。

    示例代码

    [assembly: ExportRenderer(typeof(NavigationPage), typeof(MyRenderer))]
    namespace FormsApp.iOS
    {
        class MyRenderer : NavigationRenderer
        {
            public override void PushViewController(UIViewController viewController, bool animated)
            {
                base.PushViewController(viewController, animated);
    
                var currentPage = (this.Element as Xamarin.Forms.NavigationPage)?.CurrentPage;
    
                if (this.NavigationBar == null || currentPage == null)
                    return;
    
                var buttonItems = TopViewController.NavigationItem.RightBarButtonItems;
    
                foreach (var button in buttonItems)
                {
                    if(button.Image != null){
                        button.Image = button.Image.ImageWithRenderingMode(UIImageRenderingMode.AlwaysOriginal);
                        button.TintColor = UIColor.Clear;
                    }
                    
                }
            }
        }
    }
    

    参考

    Image in Toolbar item on iOS are white(Xamarin Forms)

    【讨论】:

    • 谢谢。你能帮助如何完成这项工作吗? “为了解决这个问题,我们需要为 NavigationPage 创建一个自定义渲染器”我应该把你的代码片段放在哪里?
    • 在iOS项目中新建一个类,然后将我的代码复制进去并更改命名空间,参考docs.microsoft.com/en-us/xamarin/xamarin-forms/app-fundamentals/…
    • 感谢@ColeX -MSFT!这成功了!我只需要对非图像工具栏项进行空指针检查: if(button.Image != null)
    【解决方案2】:

    @ColeX 的解决方案 - MSFT 成功了!此外,请确保对非图像按钮进行空指针检查。

    【讨论】:

    • 如果有帮助,请考虑标记我的答案,我已经编辑了答案。
    猜你喜欢
    • 2014-04-21
    • 1970-01-01
    • 2018-05-06
    • 2014-06-13
    • 1970-01-01
    • 1970-01-01
    • 2021-05-11
    • 1970-01-01
    相关资源
    最近更新 更多