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 1 year has passed since last update.

[Swift UI]共通化したテキストフィールドで値の変更を検知方法

Posted at

結論から書くと共通化したテキストフィールドを呼んだ後にonChangeを追加すればokです。

共通化したテキストフィールド(コピペok)

いらない部分もあるので必要ない方は後で消してください

let bounds = UIScreen.main.bounds

struct common_textField: View {
    
    @Binding var text: String
    
    var body: some View {
        
        // 表示
        TextField("入力してください", text: self.$text)
            .frame(maxWidth: bounds.width * 0.5, alignment: .leading)
            .font(.system(size: 36))
            .overlay(
                RoundedRectangle(cornerSize: CGSize(width: 8.0, height: 8.0))
                    .stroke(Color.black, lineWidth: 1.0)
                    .padding(-8.0)
            )
        
    }
    
}

呼び出し

struct view1: View {

    @Binding var changeText:String

    common_textField(text: $changeText)
        //↓これ
        .onChange(of: changeText) { newValue in
            print("newValue = [\(newValue)]")
            changeText = newValue
        }
}

あとは画面遷移のタイミングでchangeTextのデータを更新させればokです

共通化した部品の場合にうまく更新されないみたいなことが結構あり、自身の忘備録も兼ねて残しておきます。

共通化したTextFieldを作ったけど、値を検知して更新する方法がわからないという方はこちらを参考にしてもらえたら幸いです。

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?