LoginSignup
7
13

More than 1 year has passed since last update.

iOSアプリケーションにキーボードショートカットのサポートを追加(UIKitとSwiftUI両方で)

Last updated at Posted at 2021-02-19

この短い記事では、アプリケーションにキーボードショートカット (keyboardShortcut, UIKeyCommand) 機能を加える方法について説明します。これは、ユーザーがiPadにキーボードを接続した状態でアプリを実行している場合に便利です。

多くの人はiPad用のキーボードカバーを購入しているので、アプリケーションにキーボードショートカットを実装しておくと便利になるでしょう。実装はほんの数分で完了します。

アプリケーションが提供するすべてのショートカットを表示するには、iPadキーボードのコマンド ⌘ キーを長押しします。それにより提供されているショートカット一覧のメニューが表示されます。

SwiftUIのアプリケーションに

修飾キー keyboardShortcut を使うことで、SwiftUIのインタラクティブなUI要素に、ショートカットキーを簡単に追加できます。

public func keyboardShortcut(_ key: KeyEquivalent, modifiers: EventModifiers = .command) -> some View

例えば、ボタンにキーボードショートカットを追加するには:

Button(action: {
    counter += 1
}, label: {
    Text("+1")
})
.keyboardShortcut("a", modifiers: [.command])

修飾キーについて

修飾キーを1つ以上設定することができます。 capsLock, shift, control, option, command, numericPad, and function.

ユーザーは、アクションを実行するために、修飾キーとあなたが定義した文字キーを押す必要があります。

例えば、キーボードショートカットを .keyboardShortcut("a", modifiers: [.command]) に設定した場合、ユーザーはコマンドキーと文字 a キーを同時に押す必要があります。

キーボードショートカットを .keyboardShortcut("r", modifiers: [.command, .option]) に設定した場合、ユーザーはコマンドキー、オプションキー、文字 r キーを同時に押す必要があります。

キーボードのショートカットを追加できるUI要素

ボタンやスイッチ(トグル)にキーボードのショートカットを追加できます。

UIKitのアプリケーションに

UIKitを使ったアプリケーションの場合、UIKeyCommand オブジェクトを作成し、与えられた一連のキーボードショートカットでkeyCommands プロパティをオーバーライドできます。

class ViewController: UIViewController {

    override var keyCommands: [UIKeyCommand]? {
        return [
            .init(title: "新しいメモを作成する", action: #selector(self.actionCreate), input: "n", modifierFlags: [.command])
        ]
    }

    @objc func actionCreate() {
        print("create")
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
    }

}

タイトル、画像、実行するアクション、修飾フラグなどを指定できます。これがドキュメンテーションに記載されている関数のコードです。

public convenience init(title: String = "", image: UIImage? = nil, action: Selector, input: String, modifierFlags: UIKeyModifierFlags = [], propertyList: Any? = nil, alternates: [UICommandAlternate] = [], discoverabilityTitle: String? = nil, attributes: UIMenuElement.Attributes = [], state: UIMenuElement.State = .off)

:relaxed: Twitter @MszPro

:sunny: 私の公開されているQiita記事のリストをカテゴリー別にご覧いただけます。

7
13
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
7
13