Xamarin iOS Hide cancel button from Search Bar
Asked Answered
L

4

6

I wanted to hide 'cancel' button in my iOS search bar. I have implemented the following custom renderer code but it seems not to to work. If anyone knows solution , please share.

public class iOSSearchBar : SearchBarRenderer 
    {
        protected override void OnElementChanged(ElementChangedEventArgs<SearchBar> args)
        {
            base.OnElementChanged(args);

        UISearchBar bar = (UISearchBar)this.Control;

        bar.AutocapitalizationType = UITextAutocapitalizationType.None;
        bar.AutocorrectionType = UITextAutocorrectionType.No;
        //bar.BarStyle = UIBarStyle.Default;
        //bar.BarTintColor = UIColor.LightGray;
        //bar.KeyboardType = UIKeyboardType.ASCIICapable;
        bar.SearchBarStyle = UISearchBarStyle.Minimal;
        bar.SetShowsCancelButton(false, false);
        bar.ShowsCancelButton = false;
}
}

Thanks in advance

Lacombe answered 21/11, 2016 at 17:25 Comment(0)
D
12

This worked for me. https://gist.github.com/xleon/9f94a8482162460ceaf9

using System;
using Xamarin.Forms.Platform.iOS;
using Xamarin.Forms;
using UIKit;
using System.Diagnostics;

[assembly: ExportRenderer(typeof(SearchBar), typeof(Namespace.iOS.Renderers.ExtendedSearchBarRenderer))]
namespace Namespace.iOS.Renderers
{
    public class ExtendedSearchBarRenderer : SearchBarRenderer
    {
        protected override void OnElementPropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
        {
            base.OnElementPropertyChanged(sender, e);

            if (e.PropertyName == "Text")
            {
                Control.ShowsCancelButton = false;
            }
        }
    }
}
Dotty answered 7/3, 2017 at 11:54 Comment(0)
S
1

Write code to hide cancel button in layoutsubviews method.

  public override void LayoutSubviews()
            {
                base.LayoutSubviews();
                UISearchBar bar = (UISearchBar)this.Control;
                bar.ShowsCancelButton = false;

            }

Following is also working or me, no need to subclass searcher:

SearchBar.TextChanged += delegate
            {
                SearchBar.ShowsCancelButton = false;

            };
Situation answered 22/11, 2016 at 6:58 Comment(0)
A
0

I think i managed to remove it manually with:

 protected override void OnElementChanged(ElementChangedEventArgs<SearchBar> e)
    {
        base.OnElementChanged(e);
        if (Control != null)
        {
            Control.Subviews[0].Subviews[0].RemoveFromSuperview();          
        }
    }
Arquebus answered 21/11, 2016 at 20:38 Comment(0)
K
0

I spend some more time searching for this, so adding here in case someone else wants to do both. In case you also need to remove the X button as well, I found the solution in this comment

Kwangtung answered 13/1, 2023 at 15:45 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.