Cross Platform
Android
iOS
 

Add an Image to a Nav Bar Button

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 uses a view controller of type UIBarButtonItemWithImageViewController that is created automatically when a project of the same name is created:

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;
    }
}

2. Add an image to the solution (named “image.png” in this case) to be used in the button.

3. 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.