Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Xamarin iOS Hide cancel button from Search Bar

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

like image 817
Jayasai Goutheman Avatar asked Nov 21 '16 17:11

Jayasai Goutheman


2 Answers

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;
            }
        }
    }
}
like image 63
Jana Filipenská Avatar answered Nov 20 '22 21:11

Jana Filipenská


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;

            };
like image 41
PlusInfosys Avatar answered Nov 20 '22 22:11

PlusInfosys