SwiftUI Preview not working with Binding<Bool> [duplicate] - swift

I present this view as a sheet from its parent view
struct NamesView: View {
#Binding var match: Match
var body: some View {
...
}
}
Since the match source of truth is in the parent view presenting this NamesView sheet, when the view is constructed I pass in a $match binding and data flows as intended.
However, when constructing this view in a preview provider
struct NamesView_Previews: PreviewProvider {
static var previews: some View {
NamesView()
}
}
the compiler says that NamesView() expects a match argument of type Binding<Match> (Match being the parent view presenting this view as a sheet). I'm not sure what would be a good way to proceed from here or if this is a limitation of SwiftUI.

If you want only constant preview, then it can be
struct NamesView_Previews: PreviewProvider {
static var previews: some View {
NamesView(match: .constant(Match()))
}
}
if you want it in live, the it can be
struct NamesView_Previews: PreviewProvider {
struct BindingTestHolder: View {
#State private var testedMatch = Match()
var body: some View {
NamesView(match: $testedMatch)
}
}
static var previews: some View {
BindingTestHolder()
}
}

Try this:
struct NamesView_Previews: PreviewProvider {
static var previews: some View {
NamesView(match:.constant(Match()))
}
}

I wrote about this in depth here, but the short version is simply to add the following extension:
extension Binding {
public static func variable(_ value: Value) -> Binding<Value> {
var state = value
return Binding<Value> {
state
} set: {
state = $0
}
}
}
And then do...
struct NamesView_Previews : PreviewProvider {
static var previews: some View {
NamesView(match: .variable(Match()))
}
}
This lets you actually mutate the value, useful when doing live previews in Xcode 14.

Related

No ObservableObject of type ModelData found: Missing environmentObject, but the environmentObject is actually there (SwiftUI, Xcode)

Xcode version: 14.2
I am trying to display a list of sports clubs. Since my modelData.clubs is still an empty array when just viewing the preview (modelData.clubs gets its actual value in my contentView, when the app is loaded), I would like it to display an array of default clubs if modelData.clubs.isEmpty. However, when I try to run my code, it gives me the following error in the marked line: Thread 1: Fatal error: No ObservableObject of type ModelData found. A View.environmentObject(_:) for ModelData may be missing as an ancestor of this view.
struct ClubList: View {
#EnvironmentObject var modelData: ModelData
#State private var sortByValue = false
var clubs: [Club] = [Club.default, Club.default, Club.default, Club.default, Club.default]
init() {
if (!modelData.clubs.isEmpty) { // ERROR IN THIS LINE
clubs = modelData.clubs
}
if sortByValue {
clubs.sort {
$0.value < $1.value
}
} else {
clubs.sort {
$0.name < $1.name
}
}
}
var body: some View {
NavigationView {
List {
ForEach(clubs) { club in
NavigationLink {
ClubDetail(club: club)
} label: {
ClubRow(club: club)
}
}
}
}
}
}
struct ClubList_Previews: PreviewProvider {
static var previews: some View {
ClubList()
.environmentObject(ModelData())
}
}
ClubList() gets called in my ContentView:
struct ContentView: View {
#EnvironmentObject var modelData: ModelData
// ... //
var body: some View {
if clubsLoaded {
ClubList()
.environmentObject(ModelData())
} // ... //
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
.environmentObject(ModelData())
}
}
And ContentView gets called in my App:
#main
struct clubsApp: App {
#StateObject private var modelData = ModelData()
var body: some Scene {
WindowGroup {
ContentView()
.environmentObject(modelData)
}
}
}
I am pretty new to Xcode, but I think I put the environmentObject(ModelData()) everywhere, where it would be required, and I am pretty lost now on what to do.
Any help would be greatly appreciated!
I think I figured it out!
This post here made me realise that my problem was that I was trying to access my modelData in init(), where it is not possible yet.
Someone from the link said:
The environment is passed down when the body is called, so it doesn't yet exist during the initialization phase of the View struct.
Thus, I solved my problem by moving
if (!modelData.clubs.isEmpty) { clubs = modelData.clubs }
from init() into its own function which is then called in onAppear of my NavigationView.

SwiftUI | Preview not updating on #Binding var value change

I am learning SwiftUI and tried to make a simple todo list but I'm having issues understanding why #Binding property doesn't update my preview.
The code is the following.
import SwiftUI
struct TodoRow: View {
#Binding var todo: Todo
var body: some View {
HStack {
Button(action: {
todo.completed.toggle()
}, label: {
Image(systemName: todo.completed ? "checkmark.square" : "square")
})
.buttonStyle(.plain)
Text(todo.title)
.strikethrough(todo.completed)
}
}
}
struct TodoRow_Previews: PreviewProvider {
static var previews: some View {
TodoRow(todo: .constant(Todo.sampleData[0]))
}
}
The preview doesn't update when I click the square button but the app works fine. Am I using it incorrectly?
EDIT:
Even without .constant(#), the preview doesn't work.
struct TodoRow_Previews: PreviewProvider {
#State private static var todo = Todo.sampleData[0]
static var previews: some View {
TodoRow(todo: $todo)
}
}
Found a solution in the article Testing SwiftUI Bindings in Xcode Previews.
In order for previews to change you must create a container view that holds state and wraps the view you're working on.
In my case what I've ended up doing was changing my preview to the following.
struct TodoRow_Previews: PreviewProvider {
// A View that simply wraps the real view we're working on
// Its only purpose is to hold state
struct TodoRowContainer: View {
#State private var todo = Todo.sampleData[0]
var body: some View {
TodoRow(todo: $todo)
}
}
static var previews: some View {
Group {
TodoRow(todo: .constant(Todo.sampleData[0]))
.previewDisplayName("Immutable Row")
TodoRowContainer()
.previewDisplayName("Mutable Row")
}
}
}

Why doesn't the Text update when using #Binding?

The Working works as expected.
But using the #Binding in the NotWorking example, doesn't seem to update the Text control. Why doesn't the #Binding version work, what am I missing here?
Initial Launch:
After Typing:
struct Working: View {
//Binding from #State updates both controls
#State private var text = "working"
var body: some View {
VStack {
TextField("syncs to label...", text: $text)
Text($text.wrappedValue)
}
}
}
struct NotWorking: View {
//Using the #Binding only updates the TextField
#Binding var text: String
var body: some View {
//This does not works
VStack {
TextField("won't sync to label...", text: $text)
Text($text.wrappedValue)
}
}
}
struct Working_Previews: PreviewProvider {
#State static var text = "not working"
static var previews: some View {
VStack {
Working()
NotWorking(text: $text)
}
}
}
Static #States don't work. It's the fact that it being static means that the struct Working_Previews isn't mutated when text is changed, so it won't refresh.
We can test this by changing from a PreviewProvider to an actual View:
struct ContentView: View {
#State static var text = "not working"
var body: some View {
VStack {
Working()
NotWorking(text: ContentView.$text)
}
}
}
This code gives the following runtime message:
Accessing State's value outside of being installed on a View. This will result in a constant Binding of the initial value and will not update.
Thanks to #George_E. I define #State in a wrapper view and display that for the preview. The WrapperView simply displays the control that I want to preview but it contains the State.
struct Working_Previews: PreviewProvider {
//Define the State in a wrapper view
struct WrapperView: View {
#State var text = "Preview is now working!!!"
var body: some View {
NotWorking(text: $text)
}
}
static var previews: some View {
VStack {
Working()
//Don't display the view that needs the #Binding
//NotWorking(text: $text)
//Use the WrapperView that has #State and displays the view I want to preview.
WrapperView()
}
}
}

Xcode preview doesn't work with generic view

I want to use generic subview in SwiftUI view.
struct UserChoiceView<DecisionView: View>: View {
let subview: DecisionView
var body: some View {
subview
.padding()
.offset(x: 10)
}
}
struct LikeDislikeView_Previews: PreviewProvider {
static var previews: some View {
UserChoiceView(subview: RoundedRectangle(cornerRadius: 10)
.fill(Color.red.opacity(0.9)))
}
}
Code above works fine, but Xcode can't generate preview.
I receive this error:
reference to generic type 'UserChoiceView' requires arguments in <...>
I think I can solve this by using AnyView type erasure, but maybe there are other workarounds.
You need to explicitly define the view in the preview.
struct UserChoiceView<DecisionView: View>: View {
let subview: DecisionView
var body: some View {
/// ...
}
}
struct LikeDislikeView_Previews: PreviewProvider {
static var decisionView: View {
// return SomeDecisionView()
}
static var previews: some View {
UserChoiceView<Self.decisionView>(subview: Self.decisionView)
}
}

Mutable Binding in SwiftUI Live Preview

I have a ChildView with a variable:
#Binding var itemName: String
In this ChildView I have few buttons that change value of the variable:
Button(action: {
self.itemName = "different value"
})
I was trying to use Preview like this:
struct ChildView_Previews: PreviewProvider {
static var previews: some View {
ChildView(itemName: "test")
}
}
But I am getting an error:
Cannot convert value of type 'String' to expected argument type
'Binding'
I am aware that I can use Preview like below. And the error will be gone and preview will work, but... itemName will have constant value, it will not be mutable now, not interactive in Live Preview:
struct ChildView_Previews: PreviewProvider {
static var previews: some View {
ChildView(itemName: .constant("test"))
}
}
How to declare a binding in SwiftUI Preview to make it interactive?
Updates to a #State variable in a PreviewProvider appear to not update the the read-only computed property previews directly. The solution is to wrap the #State variable in a test holder view. Then use this test view inside the previews property so the Live Preview refreshes correctly. Tested and working in Xcode 11.2.1.
struct ChildView: View {
#Binding var itemName: String
var body: some View {
VStack {
Text("Name: \(itemName)")
Button(action: {
self.itemName = "different value"
}) {
Text("Change")
}
}
}
}
struct ChildView_Previews: PreviewProvider {
struct BindingTestHolder: View {
#State var testItem: String = "Initial"
var body: some View {
ChildView(itemName: $testItem)
}
}
static var previews: some View {
BindingTestHolder()
}
}
If you need a value that can be changed in the live preview, I like to use this helper class:
struct BindingProvider<StateT, Content: View>: View {
#State private var state: StateT
private var content: (_ binding: Binding<StateT>) -> Content
init(_ initialState: StateT, #ViewBuilder content: #escaping (_ binding: Binding<StateT>) -> Content) {
self.content = content
self._state = State(initialValue: initialState)
}
var body: some View {
self.content($state)
}
}
Use it like so:
struct YourView_Previews: PreviewProvider {
static var previews: some View {
var yourVar = "example"
BindingProvider(yourVar) { binding in
YourView(initVar: binding)
}
}
}
This allows you to test changing the binding in the live preview.