How to include view in NavigationBar of Xamarin Forms?

后端 未结 1 765
攒了一身酷
攒了一身酷 2020-12-18 10:53

I need your help !

I work on a mobile development project, cross-platform. I use Visual Studio with Xamarin Forms. I have a SearchBar (Xamarin.Forms class), but, my

1条回答
  •  独厮守ぢ
    2020-12-18 11:32

    You need to create a custom NavigationRenderer and insert your own UISearchBar into the UIToolbar or SearchView into the ViewGroup:

    Xamarin Forms : Renderer Base Classes and Native Controls

    As an example of inserting a iOS UISearchBar into the nav bar via a custom NavigationRenderer:

    Note: In order to keep things decoupled, using the MessagingCenter allows you to pump messages around without any hardcoding event dependancies within the custom renderer.

    [assembly:ExportRenderer (typeof(NavigationPage), typeof(SeachBarNavigationRender))]
    namespace Forms.Life.Cycle.iOS
    {
        public class SeachBarNavigationRender : NavigationRenderer
        {
            public SeachBarNavigationRender () : base()
            {
            }
    
            public override void PushViewController (UIViewController viewController, bool animated)
            {
                base.PushViewController (viewController, animated);
                List toolbarItem = new List ();
                foreach (UIBarButtonItem barButtonItem in TopViewController.NavigationItem.RightBarButtonItems) {
                    if ( barButtonItem.Title.Contains( "search")) {
                        UISearchBar search = new UISearchBar (new CGRect (0, 0, 200, 25));
                        search.BackgroundColor = UIColor.LightGray;
                        search.SearchBarStyle = UISearchBarStyle.Prominent;
                        search.TextChanged += (object sender, UISearchBarTextChangedEventArgs e) => {
                            D.WriteLine(e.SearchText);
                            MessagingCenter.Send (this, "SearchText", e.SearchText);
                        };
                        barButtonItem.CustomView = search;
                    }
                    toolbarItem.Add (barButtonItem);
                }
                TopViewController.NavigationItem.RightBarButtonItems = toolbarItem.ToArray ();
            }
        }
    }
    

    0 讨论(0)
提交回复
热议问题