2

I'm not sure if I created my custom TextField properly, because I am unable to observe the value changes to an @Binded text. Running the following code, you may observe that print(text) is not executed when you manually enter text into the text field.



import SwiftUI

@main
struct TestOutWeirdTextFieldApp: App {

    @State var text: String = "" {
        didSet {
            print(text)
        }
    }

    var body: some Scene {
        WindowGroup {
            StandardTextField(placeholderText: "Enter text", defaultText: $text)
        }
    }
}


struct StandardTextField: View {

    @State var placeholderText: String {
        didSet {
            print(#line)
            print(placeholderText)
        }
    }
    @Binding var defaultText: String {
        didSet {
            print(#line)
            print(defaultText)
        }
    }
    @State var systemImage: String?
    @State var underlineColor: Color = .accentColor
    @State var edges: Edge.Set = .all
    @State var length: CGFloat? = nil
    @State var secure: Bool = false

    var body: some View {
        HStack {
            if secure {
                SecureField(placeholderText, text: $defaultText)
                    .foregroundColor(underlineColor)
            } else {
                TextField(placeholderText, text: $defaultText)
                    .foregroundColor(underlineColor)
            }
            if let systemImage = systemImage {
                Image(systemName: systemImage)
                    .foregroundColor(.white)
            }
        }
        .overlay(
            Rectangle()
                .frame(height: 2)
                .padding(.top, 35)
        )
        .foregroundColor(underlineColor)
        .padding(edges, length)
    }
}

struct StandardTextView_Previews: PreviewProvider {


    static var previews: some View {
        StandardTextField(placeholderText: "Placement text", defaultText: .constant("")).previewLayout(.sizeThatFits)
    }
}

1 Answer 1

3

Instead of didSet you need to use .onChange(of: modifier, like

    HStack {
       // ... your code here
    }
    .onChange(of: defaultText) { print($0) }      // << this !!
    .overlay(
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.