1
1

【SwiftUI】状況によってonSubmitを無効化する

Posted at

はじめに

状況によって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()
}

サンプルアプリ

Simulator Screen Recording - iPhone 15 - 2024-01-05 at 21.34.41.gif

実装

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を指定しているので以下のようになります。

スクリーンショット 2024-01-05 21.40.46.png

おわり

今回紹介したsubmitScopesubmitLabelはiOS15から使用できます。

公式ドキュメント

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