取消单击搜索栏会出现对象引用错误

时间:2018-03-08 20:25:24

标签: xamarin.forms xamarin.ios

我为搜索栏创建了一个自定义渲染器来更改其UI。自定义渲染器如下所示。问题是当我点击n取消按钮时,它会给出一个对象引用错误。有人能告诉我应该做些什么吗?

[assembly: ExportRendererAttribute(typeof(TransparentSearchBar),typeof(TransparentSearchBarRenderer))]
namespace AmerisureMobile.iOS
{
    public class TransparentSearchBarRenderer : SearchBarRenderer
    {
        protected override void OnElementChanged(ElementChangedEventArgs<SearchBar> e)
        {
            base.OnElementChanged(e);

            UISearchBar bar = this.Control;
            bar.BarTintColor = UIColor.FromRGBA(155, 155, 155, 155);
            bar.SetSearchFieldBackgroundImage(null, UIControlState.Normal);
            bar.AutocorrectionType = UITextAutocorrectionType.No;
            bar.TintColor = UIColor.FromRGBA(0, 0, 0, 0);
            bar.BackgroundColor = UIColor.FromRGBA(0, 0, 0, 0);
            bar.SearchBarStyle = UISearchBarStyle.Minimal;    
            bar.SetBackgroundImage(new UIImage(), UIBarPosition.TopAttached, UIBarMetrics.Default);
            bar.SetImageforSearchBarIcon(new UIImage(), UISearchBarIcon.Clear, UIControlState.Disabled);
            UITextField txSearchField = (UITextField)Control.ValueForKey(new Foundation.NSString("searchField"));
            txSearchField.BackgroundColor = UIColor.White;
            txSearchField.BorderStyle = UITextBorderStyle.None;
            txSearchField.Layer.BorderWidth = 1.0f;
            txSearchField.Layer.CornerRadius = 2.0f;
            txSearchField.Layer.BorderColor = UIColor.LightGray.CGColor;

        }
    }
}

1 个答案:

答案 0 :(得分:1)

尝试通过向searchbar添加委托来使用点击事件覆盖该方法。

//***
bar.Delegate = new MySearchBarDelegate();

class MySearchBarDelegate: UISearchBarDelegate
{
    public override void CancelButtonClicked(UISearchBar searchBar)
    {
        //debug here
    }
}