4
3

More than 1 year has passed since last update.

[SwiftUI]タップでキーボードを閉じる方法

Last updated at Posted at 2021-08-18

投稿の経緯

個人開発中のアプリでタップしてキーボードを閉じる機能を実装したので記録に残します。

環境

Swift version 5.4.2
Xcode version 12.5.1

extensionの実装

まず、UIApplicationを拡張します。

import Foundation
import SwiftUI

extension UIApplication {
    func closeKeyboard() {
        sendAction(#selector(UIResponder.resignFirstResponder), to: nil, from: nil, for: nil)
    }
}

簡単に何をしているか説明すると、sendActionでセレクターに対してアクションを送信し、UIResponder.resignFirstRespondernilを設定することで、最上位のファーストレスポンダがnilとなり、何もアクションしていない状態となりキーボードも閉じられます。

closeKeyboardの呼び出し

タップを検知させるパーツの.onTapGestureでcloseKeyboardを呼ぶ。
今回はColorをタップしてcloseKeyboardを呼びます。

Color.gray.opacity(0.5)
    .edgesIgnoringSafeArea(.all)
    .onTapGesture {
        UIApplication.shared.closeKeyboard()
    }           

お知らせ

現在、iOS開発案件を業務委託で募集中です(副業)。TwitterDMでご依頼をお待ちしています。

4
3
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
4
3