SwiftUI pass data to subview
var subName: String
struct SubView: View {
var subName: String
// ...
}
In the above example you don't really have a state. When the subName
property in the parent view changes, the whole SubView
is redrawn and thus provided with a new value for the subName
property. It's basically a constant (try changing it to let
, you'll have the same result).
@State var subName: String
struct SubView: View {
@State var subName: String
// ...
}
Here you do have a @State
property which is initialised once (the first time the SubView
is created) and remains the same even when a view is redrawn. Whenever you change the subName
variable in the parent view, in the SubView it will stay the same (it may be modified from within the SubView but will not change the parent's variable).
@Binding var subName: String
struct SubView: View {
@Binding var subName: String
// ...
}
If you have a @Binding
property you can directly access the parent's @State
variable. Whenever it's changed in the parent it's changed in the SubView (and the other way around) - that's why it's called binding.
Why can I not pass variables to a SwiftUI view in preview?
It cannot detect return type automatically in this case, so here are possible fixes
static var previews: some View {
// setup test dice data (d4, d5, d6)
let testDice: [Die] = [Die(sides: 4), Die(sides: 5), Die()]
return DiceListView(dice: testDice)
}
or
static var previews: some View {
// setup test dice data (d4, d5, d6)
DiceListView(dice: [Die(sides: 4), Die(sides: 5), Die()])
}
Related Topics
Using Key-Value Programming (Kvp) with Swift
Load a Pcm into a Avaudiopcmbuffer
Skaction Runaction Does Not Execute Completion Block
Swift Generics: Cannot Convert Value of Type to Expected Argument Type
Executefetchrequest Doesn't Return the Nsmanagedobject Subclass
Two Weak Variables Referencing Each Other in Swift
Swift 3: How to Pinch to Scale and Rotate Uiimageview
Rxswift: Use Zip with Different Type Observables
iOS - Arkit Node Disappear After 100M
Create PDF of Dynamic Size with Typography Using Uiview Template(S)
Swift: Switch Between Nsviewcontroller Inside Container View/Nsview
How to Get Apple Health Data by Date Wise
Hide Tab Bar in View with Push
How to Use Environment Map in Arkit
Swift Struct Doesn't Conform to Protocol Equatable
Ios-Charts Library: X-Axis Labels Without Backing Data Not Showing