Damiano Miazzi
Damiano Miazzi

Reputation: 2335

SwiftUI preview page, bindable URL?

On my AdminView_Previews, I'm trying to display my AdminView, and it is required from the view to pass a Bindable object called userInfo of type UserModel.

UserModel has a var called immagine from a URL?

Here my preview:

struct AdminView_Previews: PreviewProvider {
    static var previews: some View {
        Group {
            NavigationView{
            AdminView(dm: DataManager(), userInfo: bindModelUserInfo())
            }
            
            NavigationView{
            AdminView(dm: DataManager(), userInfo: bindModelUserInfo())
            }
            .previewDisplayName("Test")
            .background(Color(.systemBackground))
            .environment(\.colorScheme, .dark)
        }
    }
}

My bindingModelUserInfo():

func bindModelUserInfo() -> Binding<UserModel?> {
    
    var variabile : UserModel = UserModel(username: "dm1886", email: "[email protected]", userID: "test", adminLevel: "user", immagine: nil )
    
    let boolVariableBinding : Binding<UserModel?> = Binding(get: { variabile },
                                                            set: { variabile = $0! })
    return boolVariableBinding
}

If I pass nil to immagine the preview fail to load.

Any idea how to solve this issue? How can I pass an URL immagine to the preview?

On the simulator app everything works fine.

Upvotes: 1

Views: 309

Answers (1)

Christian Ray Leovido
Christian Ray Leovido

Reputation: 758

You can create a @State variable that will be fed into the userInfo like this.

struct AdminView_Previews: PreviewProvider {

    @State var mockUserInfo: UserModel = UserModel(username: "dm1886", 
                                                   email: "[email protected]", 
                                                   userID: "test", 
                                                   adminLevel: "user", 
                                                   immagine: nil)

    static var previews: some View {
        Group {
            NavigationView{
            AdminView(dm: DataManager(), userInfo: $mockUserInfo)
            }
            
            NavigationView{
            AdminView(dm: DataManager(), userInfo: $mockUserInfo)
            }
            .previewDisplayName("Test")
            .background(Color(.systemBackground))
            .environment(\.colorScheme, .dark)
        }
    }
}

Can you share the code of your AdminView as well? The variable immagine might not be working because you need to handle the case for the URL? inside the AdminView. I don't know what's inside your AdminView, but handling the path for when immagine is nil to return an EmptyView could to the trick.

Upvotes: 1

Related Questions