Reputation:
I like to make a default style for my textfields. But some parts should be customizable from the view.
I be sure that I use not the correct way, because I got a error:
struct MaxTextFieldStyle: TextFieldStyle {
@State var icon: Image?
@State var framesize: Int = 0
func _body(configuration: TextField<Self._Label>) -> some View {
HStack {
if icon != nil {
icon
.foregroundColor(Color(UIColor.systemGray4))
}
configuration
}
.padding()
.overlay {
RoundedRectangle(cornerRadius: 8, style: .continuous)
.stroke(Color(UIColor.systemGray4), lineWidth: 2)
}
if(framesize > 0) { .frame(width: framesize) }
.frame(maxWidth: .infinity, alignment: .trailing)
.keyboardType(.decimalPad)
}
}
How can I add, that if be a framesize bigger then 0, that it would added?
Upvotes: 0
Views: 78
Reputation: 614
Extracting the majority of the custom View into a function makes it easy to implement what you are asking for.
struct MaxTextFieldStyle: TextFieldStyle {
@State var icon: Image?
@State var framesize: Int = 0
func _body(configuration: TextField<Self._Label>) -> some View {
if(framesize > 0) {
makeView(configuration)
.frame(width: framesize)
.keyboardType(.decimalPad)
} else {
makeView(configuration)
.frame(maxWidth: .infinity, alignment: .trailing)
.keyboardType(.decimalPad)
}
}
func makeView(_ configuration: TextField<Self._Label>): some View {
HStack {
if icon != nil {
icon
.foregroundColor(Color(UIColor.systemGray4))
}
configuration
}
.padding()
.overlay {
RoundedRectangle(cornerRadius: 8, style: .continuous)
.stroke(Color(UIColor.systemGray4), lineWidth: 2)
}
}
}
Upvotes: 0