SwiftUI #Binding Initialize - ios

Been playing around with SwiftUI and understood the concept of BindableObjects etc so far (at least I hope I do).
I bumped into a stupid problem I can't seem to find an answer for:
How do you initialize a #Binding variable?
I have the following code:
struct LoggedInView : View {
#Binding var dismissView: Bool
var body: some View {
VStack {
Text("Hello World")
}
}
}
In my preview code, I want to pass that parameter of type Binding<Bool>:
#if DEBUG
struct LoggedInView_Previews : PreviewProvider {
static var previews: some View {
LoggedInView(dismissView: **Binding<Bool>**)
}
}
#endif
How would I go an initialize it? tried:
Binding<Bool>.init(false)
Binding<Bool>(false)
Or even:
#Binding var dismissView: Bool = false
But none worked... any ideas?

When you use your LoggedInView in your app you do need to provide some binding, such as an #State from a previous view or an #EnvironmentObject.
For the special case of the PreviewProvider where you just need a fixed value you can use .constant(false)
E.g.
#if DEBUG
struct LoggedInView_Previews : PreviewProvider {
static var previews: some View {
LoggedInView(dismissView: .constant(false))
}
}
#endif

Using Binding.constant(false) is fine but only for static previews. If you actually wanna launch a Live Preview, constant will not behave the same way as the real case as it will never be updated by your actions. I personally use Live Preview a lot, as I can play around with an isolated view.
Here is what I do for previews requiring Binding:
import SwiftUI
struct SomeView: View {
#Binding var code: String
var body: some View {
// some views modifying code binding
}
}
struct SomeView_Previews: PreviewProvider {
static var previews: some View {
PreviewWrapper()
}
struct PreviewWrapper: View {
#State(initialValue: "") var code: String
var body: some View {
SomeView(code: $code)
}
}
}

If you need a simple property that belongs to a single view you
should use #State
If you need to have complex property that may
belong to several view(like 2-3 views) you shall use
#ObjectBinding
Lastly, if you need to have property that needs to use all around views you shall use #EnvironmentObject.
Source for detail information
For your case, if you still would like to initialize your Binding variable you can use:
var binding: Binding = .constant(false)

In preview you have to use .constant(Bool(false)):
#if DEBUG
struct LoggedInView_Previews : PreviewProvider {
static var previews: some View {
LoggedInView(dismissView: .constant(Bool(false))
}
}
#endif

if you have an object like viewModel you can also use .constant()
struct View_Previews: PreviewProvider {
static var previews: some View {
View(vm:.constant(ViewModel(text: "Sample Text")))
}
}

I'm using different configurations of my view within one preview (I'm working on a custom control and want to see a different configuration of it). I've extended the implementation provided by #NeverwinterMoon in order to create multiple independent instances of a view.
struct SomeView: View {
#Binding var value: Int
var body: some View {
// some views modifying code binding
}
}
struct SomeView_Previews: PreviewProvider {
static var previews: some View {
VStack {
// The same view but with different configurations
// Configuration #1
PreviewWrapper() { value in
SomeView(value: value)
.background(Color.blue)
}
// Configuration #2
PreviewWrapper(initialValue: 2) { value in
SomeView(value: value)
.padding()
}
}
}
struct PreviewWrapper<Content: View>: View {
#State var value: Int
private let content: (Binding<Int>) -> Content
init(
initialValue: Int = 0,
#ViewBuilder content: #escaping (Binding<Int>) -> Content
) {
self.value = initialValue
self.content = content
}
var body: some View {
content($value)
}
}
}

Related

How to pass by reference in Swift - number incrementing app using MVVM

I've just started learning swift and was going to build this number-incrementing sample app to understand MVVM. I don't understand why is my number on the view not updating upon clicking the button.
I tried to update the view everytime user clicks the button but the count stays at zero.
The View
import SwiftUI
struct ContentView: View {
#ObservedObject var viewModel = CounterViewModel()
var body: some View {
VStack {
Text("\(viewModel.model.count)")
Button(action: {
self.viewModel.increment()
}) {
Text("Increment")
}
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
The ViewModel
import SwiftUI
class CounterViewModel: ObservableObject {
#ObservedObject var model = Model()
func increment() {
self.model.count += 1
}
}
The Model
import Foundation
class Model : ObservableObject{
#Published var count = 0
}
Following should work:
import SwiftUI
struct Model {
var count = 0
}
class CounterViewModel: ObservableObject {
#Published var model = Model()
func increment() {
self.model.count += 1
}
}
struct ContentView: View {
#ObservedObject var viewModel = CounterViewModel()
var body: some View {
VStack {
Text("\(viewModel.model.count)")
Button(action: {
self.viewModel.increment()
}) {
Text("Increment")
}
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
Please note:
ObservableObject and #Published are designed to work together.
Only a value, that is in an observed object gets published and so the view updated.
A distinction between model and view model is not always necessary and the terms are somewhat misleading. You can just put the count var in the ViewModel. Like:
#Published var count = 1
It makes sense to have an own model struct (or class), when fx you fetch a record from a database or via a network request, than your Model would take the complete record.
Something like:
struct Adress {
let name: String
let street: String
let place: String
let email: String
}
Please also note the advantages (and disadvantages) of having immutable structs as a model. But this is another topic.
Hi it's a bad idea to use MVVM in SwiftUI because Swift is designed to take advantage of fast value types for view data like structs whereas MVVM uses slow objects for view data which leads to the kind of consistency bugs that SwiftUI's use of value types is designed to eliminate. It's a shame so many MVVM UIKit developers (and Harvard lecturers) have tried to push their MVVM garbage onto SwiftUI instead of learning it properly. Fortunately some of them are changing their ways.
When learning SwiftUI I believe it's best to learn value semantics first (where any value change to a struct is also a change to the struct itself), then the View struct (i.e. when body is called), then #Binding, then #State. e.g. have a play around with this:
// use a config struct like this for view data to group related vars
struct ContentViewConfig {
var count = 0 {
didSet {
// could do validation here, e.g. isValid = count < 10
}
}
// include other vars that are all related, e.g. you could have searchText and searchResults.
// use mutating func for logic that affects multiple vars
mutating func increment() {
count += 1
//othervar += 1
}
}
struct ContentView: View {
#State var config = ContentViewConfig() // normally structs are immutable, but #State makes it mutable like magic, so its like have a view model object right here, but better.
var body: some View {
VStack {
ContentView2(count: config.count)
ContentView3(config: $config)
}
}
}
// when designing a View first ask yourself what data does this need to do its job?
struct ContentView2: View {
let count: Int
// body is only called if count is different from the last time this was init.
var body: some View {
Text(count, format: .number)
}
}
struct ContentView3: View {
#Binding var config: ContentViewConfig
var body: some View {
Button(action: {
config.increment()
}) {
Text("Increment")
}
}
}
}
Then once you are comfortable with view data you can move on to model data which is when ObservableObject and singletons come into play, e.g.
struct Item: Identifiable {
let id = UUID()
var text = ""
}
class MyStore: ObservableObject {
#Published var items: [Item] = []
static var shared = MyStore()
static var preview = MyStore(preview: true)
init(preview: Bool = false) {
if preview {
items = [Item(text: "Test Item")]
}
}
}
#main
struct TestApp: App {
var body: some Scene {
WindowGroup {
ContentView()
.environmentObject(MyStore.shared)
}
}
}
struct ContentView: View {
#EnvironmentObject store: MyStore
var body: some View {
List($store.items) { $item in
TextField("Item", $item.text)
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
.environmentObject(MyStore.preview)
}
}
Note we use singletons because it would be dangerous to use #StateObject for model data because its lifetime is tied to something on screen we could accidentally lose all our model data which should have lifetime tied to the app running. Best to think of #StateObject when you need a reference type in a #State, i.e. involving view data.
When it comes to async networking use the new .task modifier and you can avoid #StateObject.

cannot find $exercisePlan in scope (SwiftUI) [duplicate]

How do I generate a preview provider for a view which has a binding property?
struct AddContainer: View {
#Binding var isShowingAddContainer: Bool
var body: some View {
Button(action: {
self.isShowingAddContainer = false
}) {
Text("Pop")
}
}
}
struct AddContainer_Previews: PreviewProvider {
static var previews: some View {
// ERROR HERE <<<-----
AddContainer(isShowingAddContainer: Binding<Bool>()
}
}
In Code above, How to pass a Binding<Bool> property in an initialiser of a view?
Just create a local static var, mark it as #State and pass it as a Binding $
struct AddContainer_Previews: PreviewProvider {
#State static var isShowing = false
static var previews: some View {
AddContainer(isShowingAddContainer: $isShowing)
}
}
If you want to watch the binding:
Both other solutions [the "static var" variant AND the "constant(.false)"-variant work for just seeing a preview that is static. But you cannot not see/watch the changes of the value intended by the button action, because you get only a static preview with this solutions.
If you want to really watch (in the life preview) this changing, you could easily implement a nested view within the PreviewProvider, to - let's say - simulate the binding over two places (in one preview).
import SwiftUI
struct BoolButtonView: View {
#Binding var boolValue : Bool
var body: some View {
VStack {
Text("The boolValue in BoolButtonView = \(boolValue.string)")
.multilineTextAlignment(.center)
.padding()
Button("Toggle me") {
boolValue.toggle()
}
.padding()
}
}
}
struct BoolButtonView_Previews: PreviewProvider {
// we show the simulated view, not the BoolButtonView itself
static var previews: some View {
OtherView()
.preferredColorScheme(.dark)
}
// nested OTHER VIEW providing the one value for binding makes the trick
struct OtherView : View {
#State var providedValue : Bool = false
var body: some View {
BoolButtonView(boolValue: $providedValue)
}
}
}
Other way
struct AddContainer_Previews: PreviewProvider {
static var previews: some View {
AddContainer(isShowingAddContainer: .constant(false))
}
}

Save array that can be used throughout the app in swiftUI

I saved some data in an array and that array should be used globally through out the app. That array can be edited or deleted. I have found we can use #EnvironmentObject and tried the following
#main
struct DineApp: App {
var body: some Scene {
WindowGroup {
View1().environmentObject(BookViewModel())
}
}
BookViewModel :
class BookViewModel : ObservableObject{
#Published var bookarray = [Book]()
func saveBook (Id: Int, Name: String){
bookarray.append(Book(Id: id, Name: name ). // How to use this bookarray through out the app
}
}
View1:
struct View1: View {
#EnvironmentObject var bookviewModel : BookViewModel
var body: some View {
//Code to save book on a button click
saveBook(Id: selectedId, Name: selectedName) //Selected books will be saved.
}
}
struct View1_Previews: PreviewProvider {
static let bookViewModel = BookViewModel()
static var previews: some View {
View1().environmentObject(bookViewModel)
}
}
View4:
struct View4: View {
#EnvironmentObject var bookviewModel : BookViewModel
var body: some View {
// Display saved books in a list. But it shows empty List
List(bookviewModel.bookarray) id:\name){row in
Text(row.name)
}
}
}
struct View4_Previews: PreviewProvider {
static let bookViewModel = BookViewModel()
static var previews: some View {
View4().environmentObject(bookViewModel)
}
}
This gives me an error that EnvironmentObject should be passed from ancestor view. I couldn't understand , where to pass and how to pass. The point is I need to access the bookarray in multiple views, so I couldn't understand whats the point of passing from one view to another.
In obj-C we have appdelegate and we can store any data in it if we want to use the data globally through out the app . what is the similar in swiftUI?
EnvironmentObject should be passed from ancestor view
means that you have to inject the object into the environment on a higher level of the view hierarchy. And the views which want to have access to the object must be descendants of this view.
The top level is the #main struct, add it there for example
#main
struct SwiftUIApp: App {
var body: some Scene {
WindowGroup {
ContentView()
}
.environmentObject(BookViewModel())
}
}
View4 must be a descendant of SwiftUIApp or of ContentView

How do I update a text label in SwiftUI?

I have a SwiftUI text label and i want to write something in it after I press a button.
Here is my code:
Button(action: {
registerRequest() // here is where the variable message changes its value
}) {
Text("SignUp")
}
Text(message) // this is the label that I want to change
How do I do this?
With only the code you shared it is hard to say exactly how you should do it but here are a couple good ways:
The first way is to put the string in a #State variable so that it can be mutated and any change to it will cause an update to the view. Here is an example that you can test with Live Previews:
import SwiftUI
struct UpdateTextView: View {
#State var textToUpdate = "Update me!"
var body: some View {
VStack {
Button(action: {
self.textToUpdate = "I've been udpated!"
}) {
Text("SignUp")
}
Text(textToUpdate)
}
}
}
struct UpdateTextView_Previews: PreviewProvider {
static var previews: some View {
UpdateTextView()
}
}
If your string is stored in a class that is external to the view you can use implement the ObservableObject protocol on your class and make the string variable #Published so that any change to it will cause an update to the view. In the view you need to make your class variable an #ObservedObject to finish hooking it all up. Here is an example you can play with in Live Previews:
import SwiftUI
class ExternalModel: ObservableObject {
#Published var textToUpdate: String = "Update me!"
func registerRequest() {
// other functionality
textToUpdate = "I've been updated!"
}
}
struct UpdateTextViewExternal: View {
#ObservedObject var viewModel: ExternalModel
var body: some View {
VStack {
Button(action: {
self.viewModel.registerRequest()
}) {
Text("SignUp")
}
Text(self.viewModel.textToUpdate)
}
}
}
struct UpdateTextViewExternal_Previews: PreviewProvider {
static var previews: some View {
UpdateTextViewExternal(viewModel: ExternalModel())
}
}

What is the correct way to switch between distinct UI hierarchies with SwiftUI?

Imagine a typical app that has onboarding, sign-in/registration, and content of some kind. When the app loads you need to make some decision about which view to show. A naive implementation may look like this:
struct ContentView: View {
//assuming some centralized state that keeps track of basic user activity
#State var applicationState = getApplicationState()
var body: some View {
if !applicationState.hasSeenOnboarding {
return OnBoarding()
}
if !applicationState.isSignedIn {
return Registration()
}
return MainContent()
}
}
Obviously this approach fails because SwiftUI views require an opaque return type of some View. This can be mitigated (albeit hackishly) using the AnyView wrapper type, which provides type erasure and will allow the code below to compile.
struct ContentView: View {
//assuming some centralized state that keeps track of basic user activity
#State var applicationState = getApplicationState()
var body: some View {
if !applicationState.hasSeenOnboarding {
return AnyView(OnBoarding())
}
if !applicationState.isSignedIn {
return AnyView(Registration())
}
return AnyView(MainContent())
}
}
Is there a more correct way of doing this that doesn't require the use of AnyView? Is there functionality in the SceneDelegate that can handle the transition to a completely distinct view hierarchy?
Probably the most SwiftUI-y way to do things like these is by using the Group view:
import SwiftUI
struct ContentView: View {
#State private var applicationState = getApplicationState()
var body: some View {
Group {
if !applicationState.hasSeenOnboarding {
OnBoarding()
} else if !applicationState.isSignedIn {
Registration()
} else {
MainContent()
}
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
The most important thing to note is that, this way, you won't rely on type erasure with AnyView (to avoid if not strictly necessary).
If you want to encapsulate the initial view creation in a method don't use type erasure. Instead, use the some keyword:
import SwiftUI
struct ContentView: View {
#State private var applicationState = getApplicationState()
private func initialView() -> some View {
if !applicationState.hasSeenOnboarding {
OnBoarding()
} else if !applicationState.isSignedIn {
Registration()
} else {
MainContent()
}
}
var body: some View {
initialView()
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}

Resources