Reputation: 358
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)
Upvotes: 3
Views: 2245
Reputation: 199
Reusable custom TextField can be created by many ways, one of the way is using custom TextFieldStyle
struct CustomTextFieldStyle: TextFieldStyle {
func _body(configuration: TextField<Self._Label>)-> some View {
configuration
.padding(.horizontal, 10)
.frame(height: 42)
.background(RoundedRectangle(cornerRadius: 4).stroke(Color.gray))
.accentColor(Color.black)
}
}
And can be used like
TextField("First text field", text: $text1)
.textFieldStyle(CustomTextFieldStyle())
TextField("Second text field", text: $text2)
.textFieldStyle(CustomTextFieldStyle())
You can refer this article for some other ways to create reusable custom TextField
Upvotes: -1
Reputation: 13286
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 TextField
s 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.
Upvotes: 5
Reputation: 19
you can create an custom TextFiled by creating a subclass of UITextFiled and write the UI inside that here is an example
class UnderLineTextField: UITextField {
override func layoutSubviews() {
super.layoutSubviews()
borderView.frame = CGRect.init(x: 0, y: self.frame.size.height , width: self.frame.size.width, height: 1.0)
self.addSubview(borderView)
}
}
And you can subclass these UnderLineTextField for the textfield you need
Upvotes: 0