I have been struggling with this over and over again, so I think I'm missing something. I need to do math, make a setting, assign a value or any of a host of simple operations in reaction to some user action, such as the example shown here, and SwiftUI is wanting a View where I don't need a view. There's got to be a way around the ViewBuilder's rules. I kind of worked around this by creating an unnecessary view and executing the code I need inside the View's init(), but that seems terribly awkward.
import SwiftUI
struct ContentView: View
{
@State var showStuff = false
var body: some View
{
VStack
{
Toggle(isOn: $showStuff)
{
Text("Label")
}
if showStuff
{
UserDefaults.standard.set(true, forKey: "Something")
}
}
}
}
struct ExecuteCode : View {
init( _ codeToExec: () -> () ) {
codeToExec()
}
var body: some View {
EmptyView()
}
}
usage:
HStack {
ExecuteCode {
print("SomeView1 was re-drawn!")
print("second print")
}
SomeView1()
}
( my first way is better - you're able to write only simple code here )
HStack {
// `let _ =` works inside of View!
let _ = print("SomeView1 was re-drawn!")
SomeView1()
}
( +- the same situation as in first way. Good enough solution. )
HStack {
let _ = { // look here. "let _ =" is required
print("SomeView1 was re-drawn!")
print("second print")
}() // look here. "()" is also required
SomeView1()
}
But other dev's possibly can not understand this code (especially if it is large), so first one is a little bit better.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With