Want to offer native, in-app customer service to your users? Get going quickly with Zendesk’s Mobile SDKs. Free with Zendesk.


#172: UIMenuController Basics πŸ’¬


Menus have been a part of iOS since iOS 3. They're those little black bubbles that often contain copy/paste/etc options.

They're great for offering more intermediate or advanced features right in-context over the content they'll manipulate.

Today we'll take a look at the basics of getting them working in our own view controllers. Let's get started:

First we'll add a function for when our menu item is selected:

class SpaceshipsViewController : UIViewController {
  func copySpaceship() {
    // do the thing

Then we'll need to override a couple of functions:

extension SpaceshipsViewController {
  override func canBecomeFirstResponder() -> Bool {
    return true

  override func canPerformAction(action: Selector, withSender sender: AnyObject?) -> Bool {
    switch action {
    case Selector("copySpaceship"): return true
    default: return false

Next, we'll need to actually show our menu. There are plenty of ways to do this, but one common technique is a long press gesture recognizer:

    target: self, 
    action: Selector("showMenu")

Finally, we'll implement our showMenu function:

func showMenu() {

  let menu = UIMenuController.sharedMenuController()
  menu.menuItems = [UIMenuItem(title: "Copy", action: Selector("copySpaceship"))]

  menu.setTargetRect(view.bounds, inView: view)
  menu.setMenuVisible(true, animated: true)