Created
May 28, 2025 13:54
-
-
Save hmlongco/74d284b6c5adcea66d52f90c6bf9a298 to your computer and use it in GitHub Desktop.
Conditional Views Bad Demonstration
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// ContentView.swift | |
// ConditionalViews | |
// | |
// Created by Michael Long on 5/28/25. | |
// | |
import SwiftUI | |
// per https://www.objc.io/blog/2021/08/24/conditional-view-modifiers/ | |
extension View { | |
@ViewBuilder | |
func applyIf<M: View>(condition: Bool, transform: (Self) -> M) -> some View { | |
if condition { | |
transform(self) | |
} else { | |
self | |
} | |
} | |
} | |
struct ContentView: View { | |
@State var counter: Int = 0 | |
@State var condition: Bool = false | |
var body: some View { | |
VStack(spacing: 20) { | |
Button("Bump counter \(counter)") { | |
counter += 1 | |
} | |
Button("Toggle condition \(condition)") { | |
condition.toggle() | |
} | |
idView(counter: counter) | |
} | |
.padding() | |
.applyIf(condition: condition) { | |
$0.background(Color.red.opacity(0.15)) | |
} | |
} | |
} | |
struct idView: View { | |
var counter: Int | |
@State var id: UUID = UUID() | |
var body: some View { | |
VStack { | |
Text("\(id)") | |
Text("\(counter)") | |
} | |
} | |
} | |
#Preview { | |
ContentView() | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment