Skip to content

Instantly share code, notes, and snippets.

@mattyoung
Created March 30, 2021 17:41
Show Gist options
  • Save mattyoung/b66e4cd15fe2809a32a4cea631f60e6d to your computer and use it in GitHub Desktop.
Save mattyoung/b66e4cd15fe2809a32a4cea631f60e6d to your computer and use it in GitHub Desktop.
extension View {
/// Workaround .foregroundColor(nil) not inherit from outter view bug
///
/// ```
/// ZStack {
/// Image(systemName: "star.fill")
/// .conditional(foregroundColor: Int.random(in: 1...5) < 2 ? .green : nil)
/// }
/// .foregroundColor(.red)
/// ```
///
/// - Parameter foregroundColor: a new color or nil to inherit from outter view
/// - Returns: a modified view
@warn_unqualified_access
@ViewBuilder
func conditional(foregroundColor: Color?) -> some View {
if foregroundColor != nil {
self.foregroundColor(foregroundColor)
} else {
self
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment