Add an Image to a Nav Bar Button

PDF for offline use
Sample Code:
Related SDKs:

Let us know how you feel about this

Translation Quality


0/250

This recipe shows how to add an image to UIBarButtonItem that is added to a navigation bar.

Recipe

We’re going to add a button with a checkmark as shown in the screenshot below:

  1. First, create a UINavigationController and add a UIViewController subclass to it in the FinishedLaunching method of the AppDelegate. The example below sets the RootViewController to an instance of UIBarButtonItemWithImageViewController – a [class](https://github.com/xamarin/recipes/blob/master/ios/content_controls/navigation_controller/add_an_image_to_a_nav_bar_button/UIBarButtonItemWithImage/UIBarButtonItemWithImageViewController.cs) which we implemented in our project :
public partial class AppDelegate : UIApplicationDelegate
{
    UIWindow window;
    UIBarButtonItemWithImageViewController viewController;
    UINavigationController nav;
    public override bool FinishedLaunching (UIApplication app, NSDictionary options)
    {
        window = new UIWindow (UIScreen.MainScreen.Bounds);
        viewController = new UIBarButtonItemWithImageViewController ();
        nav = new UINavigationController (viewController);
        window.RootViewController = nav;
        window.MakeKeyAndVisible ();
        return true;
    }
}
  1. Add an image to the solution (named “image.png” in this case) to be used in the button.
  2. In the implementation of the UIBarButtonItemWithImageViewController, add a class variable for the UIBarButtonItem. Create the UIBarButtonItem instance passing it a UIImage created from the “image.png” file:
UIBarButtonItem customButton;
…
public override void ViewDidLoad ()
{
    base.ViewDidLoad ();
    customButton = new UIBarButtonItem (
    UIImage.FromFile ("image.png"),
    UIBarButtonItemStyle.Plain,
    (s, e) => {
    System.Diagnostics.Debug.WriteLine ("button tapped"); }
    );
    NavigationItem.RightBarButtonItem = customButton;
}

Additional Information

The image must have a build action of Content and be included with the solution.

Xamarin Workbook

If it's not already installed, install the Xamarin Workbooks app first. The workbook file should download automatically, but if it doesn't, just click to start the workbook download manually.