はじめに
状況によってonSubmit
を無効化したいことがあったとします。
onSubmit内で分岐処理を書けば解決する話ではありますが、SwiftUIの機能でsubmitScope
というものがあります。
上位層についているonSubmit
を一部Viewで無効化することができるようです。
Form {
TextField("Username", text: $viewModel.userName)
SecureField("Password", text: $viewModel.password)
// このテキストフィールドではonSubmitは実行されない
TextField("Tags", text: $viewModel.tags)
.submitScope()
}
.onSubmit {
guard viewModel.validate() else { return }
viewModel.login()
}
サンプルアプリ
実装
import SwiftUI
struct ContentView: View {
@State private var text = ""
@State private var isBlockSubmit = false
@State private var isShowAlert = false
var body: some View {
Form {
TextField("文字を入力してください", text: $text)
.submitScope(isBlockSubmit)
Toggle("onSubmitを無効にする", isOn: $isBlockSubmit)
}
.onSubmit {
isShowAlert = true
}
.submitLabel(.send)
.alert("送信しました", isPresented: $isShowAlert) {
Button {
print()
} label: {
Text("OK")
}
}
}
}
解説
本記事のメインであるsubmitScope
は引数にisBlocking
を取ります。
isBlocking
のデフォルトはtrueです。
isBlocking
にtrueを渡すことでonSubmit
を無効化できます。
TextField("文字を入力してください", text: $text)
+ .submitScope(isBlockSubmit)
今回メインではありませんが、記事で扱ったことのない要素があります。
それはsubmitLabel
です。
submitLabel
を指定することで、キーボードのリターンキーを変更することができます。
.onSubmit {
}
.submitLabel(.send)
今回は.send
を指定しているので以下のようになります。
おわり
今回紹介したsubmitScope
とsubmitLabel
はiOS15から使用できます。
公式ドキュメント