Search code examples
c#xamarin.iosuiactionsheet

MonoTouch - Add UIActionSheet to Top Navigation Bar of my ViewController


I've got the following UIActionSheet. How do I add it to my top navigation bar? Preferably as the far right button.

var sheet = new UIActionSheet ("");
            sheet.AddButton ("Discard Picture");
            sheet.AddButton ("Pick New Picture");
            sheet.AddButton ("Cancel");
            sheet.CancelButtonIndex = 2;

            // Dummy buttons to preserve the space for the UIImageView
            for (int i = 0; i < 4; i++) {
                sheet.AddButton("");
                sheet.Subviews[i+4].Alpha = 0; // And of course it's better to hide them
            }

            var subView = new UIImageView();
            subView.ContentMode = UIViewContentMode.ScaleAspectFill;
            subView.Frame = new RectangleF(23,185,275,210);

            // Late Steve Jobs loved rounded corners. Let's have some respect for him
            subView.Layer.CornerRadius = 10; 
            subView.Layer.MasksToBounds = true;
            subView.Layer.BorderColor = UIColor.Black.CGColor;
            sheet.AddSubview(subView);

            NavigationController.Add(sheet);

Solution

  • You can show an ActionSheet using the ShowFrom methods.

    In particular, ShowFromToolbar shows the sheet from the top toolbar button.

    Here's an example which shows the sheet in different ways depending on whether you are on tablet or phone:

        void ActionMenu()
        {
            //_actionSheet = new UIActionSheet("");
            UIActionSheet actionSheet = new UIActionSheet (
                "Customer Actions", 
                null, 
                "Cancel", 
                "Delete Customer",
                 new string[] {"Change Customer"});
    
            actionSheet.Style = UIActionSheetStyle.Default;
            actionSheet.Clicked += delegate(object sender, UIButtonEventArgs args) {
                switch (args.ButtonIndex)
                {
                    case 0: DeleteCustomer(); break;
                    case 1: ChangeCustomer(); break;
                }
            };
    
            if (UIDevice.CurrentDevice.UserInterfaceIdiom == UIUserInterfaceIdiom.Phone)
                actionSheet.ShowFromToolbar(NavigationController.Toolbar);
            else
                actionSheet.ShowFrom(NavigationItem.RightBarButtonItem, true);
        }
    

    https://github.com/slodge/MvvmCross-Tutorials/blob/master/Sample%20-%20CustomerManagement/CustomerManagement/CustomerManagement.Touch/Views/CustomerView.cs#L67