With Xcode 12, you can use Canvas's capabilities to see what your device screen looks like in real time as you code.
In this article, I'll give you some tips on how to use the useful Canvas even better. If there are good tips, I will add them as needed.
-To display a View with the @EnvironmentObject property -To display a View with @Binding property --To display only the View for the component
If you have created an instance of that class in a View with the @EnvironmentObject property wrapper so that other views always see the value of the property with @Published in the ObservableObject class, the preview for that View is: You need to add the .environmentObject (ClassName ()) modifier to the View instance like this. If this is not attached, clicking the Resume button will not be displayed on the Canvas and an error will occur.
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
.environmentObject(Manager())
}
}
For structs that have a property with the @Binding property wrapper, that property is only specified as a data type and no value is assigned. For example:
@Binding var name: String
When you want to display a preview of a structure with such properties on Canvas, an error will occur even if you enter an appropriate argument at the time of initialization. In such a case, if you specify .constant () as an argument, it will be displayed well as shown below. This is any binding in the View that you can use if you want to put some value in it. The preview code looks like this:
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView(name: .constant("Masanao Sako"))
}
}
See also Paul Hudson's Hacking with Swift. https://www.hackingwithswift.com/quick-start/swiftui/how-to-create-constant-bindings
If you are creating a View (screen part) for a component to be placed in the main View, and you want to display only the View for that component in just size rather than displaying the View for that component alone on a Canvas that is the size of the device screen. Is just the size of the View with the .previewLayout (.sizeThatFits) modifier as shown below.
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
.environmentObject(Manager())
.previewLayout(.sizeThatFits)
}
}
Recommended Posts