前提
SwiftUIを使ってTODOリストアプリを作っています。
プロフィールページにある名前を編集する際にテキストフィールド付きのアラートを出現させているのですが、Submitボタンの制御方法について質問です。
テキストフィールド付きのアラートはこちらを参考に作りました。https://sarunw.com/posts/swiftui-alert-textfield/
実現したいこと
一文字も入力していない場合、Updateボタンを押しても更新できない(actionは何も起こらず、アラートも閉じない)ようにしたいのですが、方法がわからずつまずきました。
funcとして以下のように1文字以上のときはcurrentUserNameを返すようにtextIsAppropriateをtrueにして、それ以外はfalseにしています。
Button("Update", action:{ if textIsAppropriate() { return( currentUserName = userName ) } })
func textIsAppropriate() -> Bool { if userName.count > 1 { return true } else { return false } }
該当のソースコード
import SwiftUI struct ProfileView: View { @State var showAlert: Bool = false @State var userName: String = "" @AppStorage("user_name") var currentUserName: String? var body: some View { ScrollView { VStack { HStack { Text(currentUserName ?? "User name") Button(action: { showAlert = true }, label: { Image(systemName: "pencil.tip.crop.circle") }) .alert("Update user name", isPresented: $showAlert, actions: { TextField("User name", text: $userName) Button("Update", action:{ if textIsAppropriate() { return( currentUserName = userName ) } }) Button("Cancel", role: .cancel, action: {}) }, message: { Text("Please enter User name") }) } .font(.title) .frame(maxWidth: .infinity, alignment: .leading) } .padding() .multilineTextAlignment(.leading) } .navigationTitle("Profile") } func textIsAppropriate() -> Bool { if userName.count > 1 { return true } else { return false } } } struct ProfileView_Previews: PreviewProvider { static var previews: some View { NavigationView { ProfileView() } } }
試したこと
Updateボタンに対して以下を設定したが、Updateボタン自体なくなってしまった。
.disabled(!textIsAppropriate())
補足情報(FW/ツールのバージョンなど)
swift超初心者です🙏このYoutubeを見てTODO listを作り、カスタマイズをしています。
https://www.youtube.com/playlist?list=PLwvDm4VfkdpheGqemblOIA7v3oq0MS30i
回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2022/10/31 01:24