How to Use the iOS Tooltip Menu in Your Own App

You’ve probably seen this tooltip control in some of Apple’s default apps or when editing text on iOS. This tooltip actually has a name, UIMenuController, and can be customized and used in your own app, although the API can be kind of hard to grasp.

becomeFirstResponder()

Similar to how an app has a UIView hierarchy stemming from a UIWindow, it also has a UIResponder chain, since views are inherently responders.

In order to use UIMenuController on a custom view, the view must first become the app’s first responder.

In an app, the responder object that first receives many kinds of events is known as the first responder. It receives key events, motion events, and action messages, among others.

This doesn’t entail anything too fancy, but it is important to understand the responder hierarchy when dealing with multiple UIResponder subclasses. Although the UIView base class inherits the UIResponder interface, it doesn’t automatically give a UIView instance the ability to become a first responder, which is why you can only call .becomeFirstResponder() on UIView subclasses. Some iOS controls like UITextField can become first responders by default, but for custom views, you need to override the canBecomeFirstResponder variable.

Now any instance of ResponsiveView can call .becomeFirstResponder() and become its super window’s first responder, and since the UIView base class sets its UIResponder variable canResignFirstResponder to true by default, we can call .resignFirstResponder() on ResponsiveView if we need to as well.

UIMenuController

Now that we’ve got a custom view that we can set as our app’s first responder, let’s display a tooltip over it! UIMenuController has a singleton instance you can use in your app to easily use with multiple views — this ensures you don’t show a multiple menus at once.

Notice how we have to specify our responsiveView’s frame before showing the menu. This is because UIMenuController uses this information to appropriately place itself in a suitable position in the window. By default, the menu will present itself above the first responder, with its arrow pointing downwards. You can customize this behavior of course by setting the arrow direction, specifying a different frame than the first responder’s, or even specifying a different super view for the target rect calculation.

UIMenuItem

Before we show our menu, we want to set some options to display in it first.

Example

Here’s an example of the code above in action. I prefer using a UILongPressGestureRecognizer with a minimumPressDuration of 0.3 to trigger the UIMenuController, as it mimics the default behavior in iOS.

Let me know if you have any questions or thoughts on Twitter @sdrzn!