I am creating a custom TextField view that consists of multiple adornment views. I want to be able to set up the inner TextField with view modifiers such as keyboard, capitalization, etc. that apply just to that sub-view.
Rather than creating properties for each of these I figured the best way would be to pass in a single optional ViewModifier parameter and use it something like this:
struct MySuperTextField: View {
var vm: ViewModifier?
var body: some View {
TextField(...)
.modifier( vm ?? EmptyModifier() )
// ... more views here
}
}
This doesn't work due to the associatedType in ViewModifier. Alas there is no such thing as AnyViewModifier either (and I could't figure out how to make one that worked).
Anyone manage to do something like this? I couldn't find anything searching the web.
An example would be
struct LastNameModifier: ViewModifier {
func body(content: Content) -> some View {
content
.autocapitalization(.words)
.textContentType(.familyName)
.backgroundColor(.green)
// ... anything else specific to names
}
}
struct EmailModifier: ViewModifier {
func body(content: Content) -> some View {
content
.keyboardType(.emailAddress)
.textContentType(.emailAddress)
.backgroundColor(.yellow)
// ... anything else specific to emails
}
}
and then use them with my MySuperTextField like this:
VStack {
MySuperTextField("Last Name", $lastName, vm: LastNameModifier())
MySuperTextField("Email", $email, vm: EmailModifier())
}