Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a reusable CustomTextField?

Tags:

swiftui

We can create reusable views like CardView confirming to View protocol. Like that how can we create custom reusable text fields?

As we use a TextField provided in SwiftUI like

TextField("Enter your name", text: $name)

Similarly how to create your own reusable TextField with a specific style (cornerRadius, borders)

Example: CustomTextField("Enter your name", text: $name)

like image 750
buckBoy Avatar asked Jan 23 '26 23:01

buckBoy


1 Answers

You can't subclass in SwiftUI. You can create a reusable component based around a TextField or create a modifier in order to style the TextFields throughout your app.

I would recommend the modifier approach:

struct MyTextFieldModifier: ViewModifier {
    func body(content: Content) -> some View {
        content
            .padding(8.0)
            .background(Color.white.cornerRadius(8.0))
            .shadow(radius: 24.0)
            .padding()
    }
}

And then to use it:

TextField("Title", text: self.$text)
  .modifier(MyTextFieldModifier()) // Your TextField will now have a shadow and a background.

enter image description here

like image 109
arsenius Avatar answered Jan 25 '26 22:01

arsenius



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!