Get Updates By E-mail 

Article Written By:
Johann Dowa

Example: How To Place An Image In A UIMenuItem By Using Method Swizzling

I’ve seen this question the question of how to place an image in a UIMenuItem come up before – and seen some completely custom menu implementations, but here’s one very simple solution that uses Objective-C method swizziling.

Here’s a project from CHEN Xian’an that uses method swizzling to allow you to use custom images in your UIMenuItem’s.  The provides a category extending UIMenuItem so that it can work with custom UIMenuItem classes you may already be using such as the blocks supporting PSMenuItem.

Here’s an image showing the solution in action:

Image UIMenuItem

As the developer states in the readme:

UIMenuItem uses UILabel to display its title, that means we can swizzle –drawTextInRect: to support image.

UIMenuItem+CXAImageSupport is a dirty hack but should be safe in most cases.

You can find UIMenuItem+CXAImageSUpport on Github here.

A great example of how you can use method swizzling to enhance UIKit components.

Submit A Resource

Have you created a useful tutorial, library or tool for iOS development that you would like to get in front of our 300,000+ monthly page views from iOS developers?

You can submit the url here.

The resources we feel will appeal to our readers the most will be posted on the front page.