I'm trying to use SwiftUI's @State in playground. Here's my code:
import UIKit
import PlaygroundSupport
import SwiftUI
struct ContentView: View {
@State private var showGreeting = false
var body: some View {
Form {
Button(action: {
self.showGreeting.toggle()
}) {
Text("Toggle Greeting")
}
if showGreeting {
Text("Hello World!")
}
}
}
}
let viewController = UIHostingController(rootView: ContentView())
PlaygroundPage.current.liveView = viewController
I can see the button on the live view. But if I click it, it doesn't show the text. A second click does reveal the text. Further clicks don't seem to make any difference visually.
On each click, I get the following message in log area:
=== AttributeGraph: cycle detected through attribute 38 ===
Need some help understanding what this means in this context and why the state is not behaving naturally.
Note: I'm running macOS Mojave, so I don't have option of SwiftUI previews. I'm making do with live preview of playgrounds.
There's nothing wrong with your SwiftUI, and it runs fine when pasted into a new project.
If you change the Form to a VStack, it works fine in the playground. Using a List gives you the same error. Maybe a bug, I'd report it to Apple.
In my experience, if you're stuck on Mojave for the time being, just set up a project where you can run the simulator. It takes just a couple seconds to compile and run, and you wind up saving time when your SwiftUI playgrounds crash, get weird errors like this, etc.
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