The code below works:
struct ContentView: View {
var body: some View {
Text("Hello, world!")
.customViewModifier(modifier: { view in CustomModifier(content: { view } )} )
}
}
struct CustomModifier<Content: View>: View {
let content: () -> Content
var body: some View {
content()
.foregroundColor(.red)
}
}
extension View {
func customViewModifier<ContentModifier: View>(modifier: (Self) -> ContentModifier) -> some View {
return modifier(self)
}
}
My goal is to be able the code below. Currently, Xcode does not help me to fix the error.
struct ContentView: View {
var body: some View {
Text("Hello, world!")
.customViewModifier(modifier: CustomModifier)
}
}
Is there a way around to make my goal possible?
here was my try to solve the issue:
extension View {
func customViewModifier2<ContentModifier: View>(modifier: (Self) -> ((Self) -> ContentModifier)) -> some View {
return modifier(self)
}
}
Error:
Type '(Self) -> ContentModifier' cannot conform to 'View'
CodePudding user response:
The final real goal is not clear ('cause it is really better to use ViewModifier
based approach), but if you want to use a type as argument it can be like the following
*compiled with Xcode 13.2 / iOS 15.2
struct ContentView: View {
var body: some View {
Text("Hello, world!")
.customViewModifier(modifier: CustomModifier.self) // << type !!
}
}
extension View {
func customViewModifier(modifier: CustomModifier<Self>.Type) -> some View {
return modifier.init(content: { self })
}
}