Xamarin Forms Searchbar iOS 13 ignores background color

Viewed 2698

It seems the latest version of iOS (13) ignores the searchbar background color?

iOS 13 Changes to UISearchBar tint's, can't achieve the same outcome

I'm using this and it works on all versions below, but on 13 it ignores the background color and makes it white

  <SearchBar HeightRequest="35" BackgroundColor="#2A4880" TextColor="White"></SearchBar>

Is this a known issue? Is there a work around?

4 Answers

You can solve this by creating a PlatformEffect:

App.xaml.cs

[assembly: ResolutionGroupName("ProjectName")]
namespace ProjectName.App
{
    public partial class App : Application
    {
        ...

Shared project:

public class SearchBarBackgroundEffect : RoutingEffect
    {
        public SearchBarBackgroundEffect() : base("ProjectName.SearchBarBackgroundEffect") { }
    }

iOS project:


[assembly: ExportEffect(typeof(SearchBarBackgroundPlatformEffect), "SearchBarBackgroundEffect")]
 public class SearchBarBackgroundPlatformEffect : PlatformEffect
    {
        private UISearchBar NativeSearchBar => (UISearchBar)Control;
        private SearchBar XamarinSearchBar => (SearchBar)Element;

        protected override void OnAttached()
        {
            if (UIDevice.CurrentDevice.CheckSystemVersion(13, 0))
                NativeSearchBar.SearchTextField.BackgroundColor = XamarinSearchBar.BackgroundColor.ToUIColor();
        }

        protected override void OnDetached()
        {
             // Intentionally left blank.
        }
    }

XAML File

 <SearchBar>
                <SearchBar.Effects>
                    <effects:SearchBarBackgroundEffect />
                </SearchBar.Effects>
            </SearchBar>

If you are facing this issue, this definitely is a bug that needs to be fixed by Xamarin Forms.

It was introduced in iOS 13 when a new Property was introduced. As I mentioned here, they have to place a conditional check for iOS 13 and set the BackgroundColor of the SearchBar.

You could open an issue in Xamarin Forms on GitHub, and for now use a CustomRenderer to fix this locally.

The issue on GitHub is https://github.com/xamarin/Xamarin.Forms/issues/8041

The simplest renderer with fix

using App.Mobile.iOS.CustomRenderers;
using UIKit;
using Xamarin.Forms;
using Xamarin.Forms.Platform.iOS;

[assembly: ExportRenderer(typeof(SearchBar), typeof(FixedSearchBarRenderer))]
namespace App.Mobile.iOS.CustomRenderers
{
    public class FixedSearchBarRenderer : SearchBarRenderer
    {
        protected override void OnElementChanged(ElementChangedEventArgs<SearchBar> e)
        {
            base.OnElementChanged(e);

            if (UIDevice.CurrentDevice.CheckSystemVersion(13, 0) && Control != null)
            {
                Control.SearchTextField.BackgroundColor = UIColor.FromRGB(255, 255, 255);
            }
        }
    }
}
Related