Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a simple Binding for previews

Tags:

swiftui

With the new @Binding delegate and previews, I find it kinda awkward to always have to create a @State static var to create the neccesarry binding:

struct TestView: View {     @Binding var someProperty: Double     var body: some View {         //...     } }  #if DEBUG struct TestView_Previews : PreviewProvider {     @State static var someProperty = 0.7     static var previews: some View {         TestView(someProperty: $someProperty)     } } #endif  

Is there a simpler way to create a binding, that proxies a simple values for testing and previewing?

like image 334
reckter Avatar asked Jun 06 '19 21:06

reckter


People also ask

How do I create a binding in SwiftUI?

In SwiftUI, you can create bindings in 2 ways: With the @Binding property wrapper, which creates a binding, but doesn't store it. With other property wrappers, like @State, which creates a binding, and also stores its value.

What is the app Xcode previews?

Overview. When you create a custom View with SwiftUI, Xcode can display a preview of the view's content that stays up-to-date as you make changes to the view's code. You define a structure that conforms to the PreviewProvider protocol to tell Xcode what to display. Xcode shows the preview in a canvas beside your code.

What is PreviewProvider in SwiftUI?

A type that produces view previews in Xcode.

What is binding string Swift?

String in swift is a value type, so your textValue property is taking a copy of the value, and SwiftUI is monitoring that copy, not the actual value in Controller.message . What you want here is a binding or an observed object—exactly which depends on whether Controller is a struct or a class type.


1 Answers

You can use .constant(VALUE) in your Previews, no need to create a @State.

/// A value and a means to mutate it. @propertyWrapper public struct Binding<Value> {      /// Creates a binding with an immutable `value`.     public static func constant(_ value: Value) -> Binding<Value> } 

e.g.

TestView(someProperty: .constant(5.0)) 
like image 51
Matteo Pacini Avatar answered Sep 28 '22 04:09

Matteo Pacini