【问题标题】:How to make "Cancel" on iOS searchbar clickable when keyboard is not focused? [Xamarin Forms]当键盘没有聚焦时,如何在 iOS 搜索栏上点击“取消”? [Xamarin 形式]
【发布时间】:2020-06-04 16:08:48
【问题描述】:

我目前正在尝试调整 Xamarin.Forms iOS SearchBar 以在向搜索栏添加文本时显示“取消”按钮(不是通过键盘,而是通过类别单击)。我用下面的代码成功地做到了这一点。现在的问题是,我希望“取消”按钮一旦出现就可以点击。

目前我正在做以下事情:

单击更改搜索栏文本的命令 -> 有效

显示取消按钮 -> 有效

取消按钮是可点击的 -> 不起作用。它是灰色的。我需要点击搜索栏(这样键盘才会出现)让它变成蓝色并且可以点击。

这是我的代码:

[assembly: ExportRenderer(typeof(CustomSearchBar), typeof(SearchBar_iOS))]
namespace Project.iOS.Renderers
{
  public class SearchBar_iOS : SearchBarRenderer
  {
    protected override void OnElementChanged(ElementChangedEventArgs<Xamarin.Forms.SearchBar> e)
    {
        base.OnElementChanged(e);
        var element = e.NewElement as CustomSearchBar;

        if (Control != null && element != null)
        {
            this.Control.TextChanged += (s, ea) =>
            {
                //if (ea.SearchText == "")
                this.Control.ShowsCancelButton = true;
            };

            this.Control.OnEditingStarted += (s, ea) => //when control receives focus
            {
                this.Control.ShowsCancelButton = true;
            };

            this.Control.OnEditingStopped += (s, ea) => //when control looses focus 
            {
                this.Control.ShowsCancelButton = false;
            };

            Control.BackgroundColor = Color.Transparent.ToUIColor();
            Control.Layer.CornerRadius = 10;
            Control.ClipsToBounds = true;
            Control.SearchBarStyle = UISearchBarStyle.Minimal;
        }
    }

在我的渲染器中是否有一个调用可以在添加文本时强制它成为可点击的?

【问题讨论】:

    标签: c# xamarin xamarin.forms xamarin.ios


    【解决方案1】:

    这已经在此处针对 iOS 原生进行了讨论: How do you keep the cancel button in the search bar enabled when the keyboard is dismissed?

    但是,iOS 似乎不希望您弄乱“取消”按钮的行为,否则他们会公开暴露它。也就是说,在您的 OnEditingStopped 事件的自定义渲染器中尝试此操作(我的快速测试有效):

     this.Control.OnEditingStopped += async (s, ea) => //when control looses focus 
     {
          this.Control.ShowsCancelButton = false;
          var searchBar = this.Control;
          BeginInvokeOnMainThread(() =>
          {
              var cancelButton = searchBar.ValueForKey(new NSString("cancelButton")) as UIButton;
              cancelButton.Enabled = true;
           });
      };
    

    存在被 Apple 拒绝或其他未发现问题的风险,所以如果它不起作用,请不要对我大喊大叫。 :-)

    此外,由于取消按钮无法公开访问,除非通过 ValueForKey 方法访问它,因此 Apple 可以随时更改密钥名称,这会破坏这种骇人听闻的解决方法。

    【讨论】:

    • 效果很好。谢谢!对 Apple 的做法很感兴趣,如果他们拒绝这样做,可能必须制定自定义解决方案。
    猜你喜欢
    • 2014-09-23
    • 2018-01-28
    • 2015-07-07
    • 2016-05-04
    • 2016-06-19
    • 2019-01-31
    • 1970-01-01
    • 2022-11-15
    • 2019-05-16
    相关资源
    最近更新 更多