I am making my View Identifiable like this code:
struct RedView: View, Identifiable {
let id: UUID = UUID()
var body: some View {
Color.red.frame(width: 100, height: 100, alignment: .center)
}
}
Now I want make a CustomViewModifier which only work or be applicable on Views which they are Identifiable, for example to make normal ViewModifier, we do not need that our content conform to Identifiable, they must just conform to View, In this question/problem I want make a CustomViewModifier which require it contents conform to View and Identifiable, how can I do this?
here what tried so far, need help to complete:
struct CustomViewModifier<InPutContent: View & Identifiable>: ViewModifier {
func body(content: InPutContent) -> some View {
return content.onAppear() { print(content.id) }
}
}
use case:
import SwiftUI
struct ContentView: View {
var body: some View {
RedView()
.modifier(CustomViewModifier()) // It must work! because RedView is Identifiable!
Text("Hello")
.modifier(CustomViewModifier()) // It must NOT work! because Text is not Identifiable!
}
}
UPDATE:
struct CustomViewModifier<InPutContent: View & Identifiable>: ViewModifier {
var inPutContent: () -> InPutContent
func body(content: Content) -> some View {
return body2(content: inPutContent())
}
func body2(content: InPutContent) -> some View {
return content.onAppear() { print(content.id) }
}
}
use case:
import SwiftUI
struct ContentView: View {
var body: some View {
RedView()
.modifier(CustomViewModifier(inPutContent: { RedView() })) // compiles
Text("Hello")
.modifier(CustomViewModifier(inPutContent: { Text("Hello") })) // does not compile
}
}