Apologies for the title.
I don't know how to word this question properly because I have trouble finding what this is called.
Please allow me to ask this question using examples instead...
Basically I want to turn this:
struct MyTextField: View {
var body: some View {
VStack(alignment: .leading) {
Text("Label")
TextField("", text: .constant(""), axis: .vertical)
.textFieldStyle(MyTextFieldStyle())
}
.padding()
}
}
struct MyTextFieldStyle: TextFieldStyle {
func _body(configuration: TextField<Self._Label>) -> some View {
configuration
.padding()
.overlay {
RoundedRectangle(cornerRadius: 5, style: .continuous)
.stroke(.secondary, lineWidth: 1)
}
}
}
Into this:
struct MyTextField: View {
var body: some View {
VStack(alignment: .leading) {
Text("Label")
TextField("", text: .constant(""), axis: .vertical)
.textFieldStyle(.myTextFieldStyle)
}
.padding()
}
}
struct MyTextFieldStyle: TextFieldStyle {
func _body(configuration: TextField<Self._Label>) -> some View {
configuration
.padding()
.overlay {
RoundedRectangle(cornerRadius: 5, style: .continuous)
.stroke(.secondary, lineWidth: 1)
}
}
}
Note that the only difference is
.textFieldStyle(MyTextFieldStyle())
vs
.textFieldStyle(.myTextFieldStyle)
I thought I could achieve this using an extension to TextField but it didn't seem to work:
extension TextField {
var caviaTextFieldStyle: CaviaTextFieldStyle {
.init()
}
}
----- answered -----
So the solution is:
extension TextFieldStyle where Self == MyTextFieldStyle {
static var myTextFieldStyle: MyTextFieldStyle {
.init()
}
}
Try:
extension TextFieldStyle {
static var myTextFieldStyle {
return MyTextFieldStyle()
}
}
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments