DropDownMenuRenderer.cs 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. using System;
  2. using Xamarin.Forms;
  3. using Xamarin.Forms.Platform.iOS;
  4. using UIKit;
  5. using System.Linq;
  6. using CoreGraphics;
  7. using System.Collections.Generic;
  8. using System.Windows.Input;
  9. // [assembly: Xamarin.Forms.ExportRenderer(typeof(ContentPage), typeof(InABox.Mobile.DropDownMenuRenderer))]
  10. namespace InABox.Mobile
  11. {
  12. public class DropDownMenuRenderer : PageRenderer
  13. {
  14. //I used UITableView for showing the menulist of secondary toolbar items.
  15. List<ToolbarItem> _secondaryItems;
  16. UITableView table;
  17. protected override void OnElementChanged(VisualElementChangedEventArgs e)
  18. {
  19. //Get all secondary toolbar items and fill it to the gloabal list variable and remove from the content page.
  20. if (e.NewElement is ContentPage page)
  21. {
  22. _secondaryItems = page.ToolbarItems.Where(i => i.Order == ToolbarItemOrder.Secondary).ToList();
  23. _secondaryItems.ForEach(t => page.ToolbarItems.Remove(t));
  24. }
  25. base.OnElementChanged(e);
  26. }
  27. public override void ViewWillAppear(bool animated)
  28. {
  29. var element = (ContentPage)Element;
  30. //If global secondary toolbar items are not null, I created and added a primary toolbar item with image(Overflow) I
  31. // want to show.
  32. if (_secondaryItems != null && _secondaryItems.Count > 0)
  33. {
  34. element.ToolbarItems.Clear();
  35. element.ToolbarItems.Add(new ToolbarItem()
  36. {
  37. Order = ToolbarItemOrder.Primary,
  38. Text = "Tools",
  39. //Icon = "more.png",
  40. Priority = 1,
  41. Command = new Command(() =>
  42. {
  43. ToolClicked();
  44. })
  45. });
  46. }
  47. base.ViewWillAppear(animated);
  48. }
  49. //Create a table instance and added it to the view.
  50. private void ToolClicked()
  51. {
  52. if (table == null)
  53. {
  54. var items = _secondaryItems.Where(x => (!(x is HideableToolbarItem)) || (((HideableToolbarItem)x).IsVisible)).ToList();
  55. //Set the table position to right side. and set height to the content height.
  56. var childRect = new CGRect((float)View.Bounds.Width - 250, 0, 250, items.Count() * 56);
  57. table = new UITableView(childRect)
  58. {
  59. Source = new DropDownMenuSource(items)
  60. };
  61. Add(table);
  62. return;
  63. }
  64. foreach (var subview in View.Subviews)
  65. {
  66. if (subview == table)
  67. {
  68. table.RemoveFromSuperview();
  69. return;
  70. }
  71. }
  72. Add(table);
  73. }
  74. }
  75. }