---
title: "#172: UIMenuController Basics 💬"
url: https://littlebitesofcocoa.com/172-uimenucontroller-basics
author: Jake Marsh
published: 2016-01-19
topics: ["UIKit"]
description: "Menus have been a part of iOS since iOS 3. They're those little black bubbles that often contain copy/paste/etc options."
---

# #172: UIMenuController Basics 💬

By Jake Marsh, January 19, 2016. HTML: https://littlebitesofcocoa.com/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:

``` swift
class SpaceshipsViewController : UIViewController {
  func copySpaceship() {
    // do the thing
  }
}
```

Then we'll need to **override** a couple of **functions**:

``` swift
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**:

``` swift
view.addGestureRecognizer(
  UILongPressGestureRecognizer(
    target: self, 
    action: Selector("showMenu")
  )
)
```

Finally, we'll implement our `showMenu` **function**:

``` swift
func showMenu() {
  becomeFirstResponder()

  let menu = UIMenuController.sharedMenuController()
  menu.menuItems = [UIMenuItem(title: "Copy", action: Selector("copySpaceship"))]

  menu.setTargetRect(view.bounds, inView: view)
  menu.setMenuVisible(true, animated: true)
}
```

Success!

<img src='https://media.littlebitesofcocoa.com/bite-assets/172-uimenucontroller-basics-menu-example.png' style='max-width: 55px;' />
