Processing shift-tab (backtab) events in NSTextView

February 21, 2020

I'm writing a Mac App which includes an NSTextView. One of the things I found difficult to discover online is how to respond to when the user presses shift-tab while editing in the text view - I wanted to intercept this event to de-indent a list item.

Turns out this is called a "backtab" and NSTextView has a built in way for consumers to respond to it, as part of NSTextViewDelegate. You implement the doCommandBy function and check for #selector(insertBacktab(_:))

extension MyViewController: NSTextViewDelegate {
    func textView(
        _ textView: NSTextView,
        doCommandBy commandSelector: Selector
    ) -> Bool {
        if commandSelector == #selector(insertBacktab(_:)) {
            print("Handling the backtab!")
            return true
        }
        return false
    }
}

Note: we return true to indicate that the event was handled, which prevents any other default behavior. We need to return false otherwise, since we still want other commands (like inserting newlines) to work correctly.

Tweet This
Get New Posts Via Email
Picture of me with a corgi

Noah Gilmore

I'm Noah, a software developer based in the San Francisco Bay Area. I focus mainly on full stack web and iOS development

  • 💻 I co-founded Replo, a no-code platform for e-commmerce
  • ✍️ You can read technical posts on my blog
  • 📱 I wrote an app which lets you create transparent app icons called Transparent App Icons
  • 🧩 I made a puzzle game for iPhone and iPad called Trestle
  • 🎨 I wrote a CoreImage filter utility app for iOS developers called CIFilter.io
  • 👋 Please feel free to reach out on Twitter / 𝕏