きっかけ
特定の条件下でのみ、画像の色を変更したいという場合があったので、
それを実装するために調べてみた。
方法
extension View {
@ViewBuilder
func `if`<Content: View>(
_ condition: Bool, transform: (Self) -> Content
) -> some View {
if condition {
transform(self)
} else {
self
}
}
}
呼び出し方
ContentView.swift
Image("testImage")
.renderingMode(.template)
.if(viewModel.iconName == "testIcon1") {
$0.foregroundColor(Color.blue)
}