0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

【SwiftUI】背景タップで TextField() を下げる

Posted at

目的

・背景をタップすることで TextField() を下げる

使用する場面

・チャットアプリ
・文字を入力するもの全般

重要なプログラム

① : タップを検知する

// ① : タップを検知する
.onTapGesture {
    // TextField() を下げる関数の呼び出し
    UIApplication.shared.closeKeyboard()
}

② : TextField() を下げる(閉じる)

// ② : TextField() を下げる(閉じる)
extension UIApplication {
    func closeKeyboard() {
        sendAction(#selector(UIResponder.resignFirstResponder), to: nil, from: nil, for: nil)
    }
}

完成

ContentView.swift
import SwiftUI

struct ContentView: View {
    @State var name: String = ""

    var body: some View {
        ZStack {
            // 背景はオレンジ色
            Color.orange
                .opacity(0.4)
                .edgesIgnoringSafeArea(.all)
                // ① : タップを検知する
                .onTapGesture {
                    UIApplication.shared.closeKeyboard()
                }
            
            VStack {
                Text("Input: ") + Text(name)
                TextField("Placeholder", text: $name)
                    .padding()
                    .border(Color.white, width: CGFloat(3))
            }
        }
    }
}

// ② : TextField() を下げる(閉じる)
extension UIApplication {
    func closeKeyboard() {
        sendAction(#selector(UIResponder.resignFirstResponder), to: nil, from: nil, for: nil)
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

確認

extension とは

既にあるクラスに機能を追加する

TextField() を上げるには

UIResponder.resignFirstResponder (上げる)

UIResponder.keyboardWillShowNotification (下げる)

参考文献

0
1
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
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?