Last active
April 29, 2023 07:16
-
-
Save kntkymt/ebf6932debea175560194bc0baac87aa to your computer and use it in GitHub Desktop.
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
import SwiftUI | |
public extension View { | |
func extend<Content: View>(@ViewBuilder transform: (Self) -> Content) -> some View { | |
transform(self) | |
} | |
func `if`<T: View, F: View>(_ condition: Bool, @ViewBuilder _ then: (Self) -> T, @ViewBuilder `else`: (Self) -> F) -> some View { | |
condition ? ViewBuilder.buildEither(first: then(self)) : ViewBuilder.buildEither(second: `else`(self)) | |
} | |
} | |
struct ContentView: View { | |
@State var toggle = false | |
var body: some View { | |
VStack { | |
TextView() | |
Button { | |
toggle.toggle() | |
} label: { | |
Text("toggle if") | |
} | |
} | |
.if(toggle) { content in | |
content.overlay { | |
Text("true condition") | |
} | |
} else: { content in | |
content | |
} | |
// .extend { content in | |
// if toggle { | |
// content.overlay { | |
// Text("true condition") | |
// } | |
// } else { | |
// content | |
// } | |
// } | |
} | |
} | |
final class ViewModel: ObservableObject { | |
@Published var count = 0 | |
} | |
struct TextView: View { | |
@StateObject var viewModel: ViewModel | |
init() { | |
_viewModel = .init(wrappedValue: ViewModel()) | |
} | |
var body: some View { | |
let _ = Self._printChanges() | |
Button { | |
viewModel.count += 1 | |
} label: { | |
Text("count: \(viewModel.count)") | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment