MonoTouch – Adding Button To UIViewController Toolbar

This is going to be a short post.  I was recently looking at how to add a button to the toolbar of a UIView in MonoTouch.  I found a number of examples, but none seemed to work for me.  The toolbar would show, but the button would not.

To add a button to the toolbar, we will need to use a UIBarButtonItem and add it to the ToolbarItems property of the UIViewController.  This will be done in the ViewDidLoad override event.

private UIBarButtonItem deleteButton = null;

public override void ViewDidLoad()
{
     base.ViewDidLoad();
     deleteButton = new UIBarButtonItem(UIBarButtonSystemItem.Trash, HandleDeleteClicked);
     this.ToolbarItems = new UIBarButtonItem[] { deleteButton };
}

private void HandleDeleteClicked(object sender, EventArgs e)
{
     Console.WriteLine("Delete button clicked");
}

In the code, we create a new instance of the UIBarButtonItem, using the constructor overload that accepts the UIBarButtonSystemItem and Event Handler.  Since I want the button to be the standard “Trash” button of iOS, I use the UIBarButtonSystemItem.Trash value.  The event handler will get executed when the button is clicked.  After that, we set the ToolbarItems property of the UIViewController to a new array containing our button.

The reason I made the button declaration as a class declaration is because it seems that MonoTouch is sometimes very aggressive with garbage collection. With the variable being a class declaration, it won’t be garbage collected until the view is garbage collected.


Tagged: , ,

Leave a comment

Your email address will not be published. Required fields are marked *