how to set position of cursor at beginning for xamarin forms search bar

hi all,
i want to set cursor at the beginning position for xamarin forms search bar after search bar text is filled.
example:
mysearchbar.text="Hello";
now i want to set Position of Cursor of mysearchbar at beginning(starting ) of it.
any solution?
thanks in advance :smile:

Answers

  • ColeXColeX Member, Xamarin Team Xamurai
    edited September 2018

    You would need custom renderer to do this stuff .

    Step 1 : Find the entry(EditText in android, UITextField in iOS) inside the searchbar .

    Step 2 : Assign the text change event, set cursor position .

    Android:

    [assembly: ExportRenderer(typeof(SearchBar), typeof(CustomSearchBarRenderer))]
    namespace PCL.Droid
    {
        class CustomSearchBarRenderer : SearchBarRenderer
        {
            public CustomSearchBarRenderer(Context context) : base(context)
            {
            }
    
            protected override void OnElementChanged(ElementChangedEventArgs<SearchBar> e)
            {
                base.OnElementChanged(e);
    
                if (Control != null)
                {
                    int id = Control.Resources.GetIdentifier("android:id/search_src_text", null, null);
                    EditText edittext = Control.FindViewById(id) as EditText;
                    edittext.TextChanged += Edittext_TextChanged;
                }
            }
    
            private void Edittext_TextChanged(object sender, Android.Text.TextChangedEventArgs e)
            {
                if (Control.HasFocus)
                {
                    (sender as EditText).SetSelection(0);
                }
            }
        }
    }
    

    iOS

    [assembly: ExportRenderer(typeof(SearchBar), typeof(CustomSearchBarRenderer))]
    namespace PCL.iOS
    {
        class CustomSearchBarRenderer : SearchBarRenderer
        {
            protected override void OnElementChanged(ElementChangedEventArgs<SearchBar> e)
            {
                base.OnElementChanged(e);
    
                if(Control != null)
                {
                    foreach(var view in Control.Subviews)
                    {
                        foreach(var view1 in view.Subviews)
                        {
                            if (view1 is UITextField)
                            {
                                UITextField textField = view1 as UITextField;
                                textField.AddTarget((sender, e1)=> {
                                    var position = textField.BeginningOfDocument;
                                    textField.SelectedTextRange = textField.GetTextRange(position, position);
                                }, UIControlEvent.EditingChanged);
                                break;
                            }
                        }                  
                    }
                }          
            }
        }
    }
    
Sign In or Register to comment.