Using data with different files - swift

I'm trying to display the name that the user enters in the text field, but when I launch the app, it only shows 'The player is'. I tried to assign the value of player1Name immediately to a string and it worked
This is my first view
class PlayerList : ObservableObject {
#Published var player1Name = ""
}
struct Player : Identifiable {
var name : String
let id = UUID()
}
struct ViewJouer: View {
#ObservedObject var player = PlayerList()
#Environment(\.presentationMode) var presentationMode
var body: some View {
VStack {
TextField("Enter player name", text: $player.player1Name)
}
This is my second view:
struct ViewTest: View {
#ObservedObject var player = PlayerList()
var body: some View {
Text("The player is \(player.player1Name)")
}
}

Related

TextField in SwiftUI resets after every keystroke

in this script the TextField is shown, but it resets to "player 1" after every keystroke. Can anyone help me?
import SwiftUI
class Player: ObservableObject {
#Published var playerData = "player 1"
}
let player = Player()
struct ContentView: View {
#ObservedObject var player: Player
var body: some View {
TextField("player", text: $player.playerData)
}
}
Tried with other code, but without success.
class Player: ObservableObject {
#Published var playerData = "player 1"
static let shared = Player()
}
struct ContentView: View {
#ObservedObject var player = Player.shared
var body: some View {
TextField("player", text: $player.playerData)
}
}
However, usually the model store would be an environmentObject PlayerStore and would contain an array of Player model structs.

How to assign a value selected from a Picker to a variable in another class?

I would like to use a picker to select a value and store that value in a variable contained in another class. How can I do that? Here is my code:
my contentview
struct ContentView: View {
#State public var selectedOperator = ""
#ObservedObject var bitwiseCalculator = BitwiseCalculator()
let operators = ["AND", "OR", "XOR"]
var body: some View {
VStack {
Picker("Operator", selection: $selectedOperator) {
ForEach(operators, id: \.self) { op in
Text(op)
}
}
}
}
}
and the variable in the class where I want to save it
class BitwiseCalculator: ObservableObject {
#Published var bitwiseOperator = ""
}
Use
$bitwiseCalculator.bitwiseOperator
& switch your
#ObservedObject to #StateObject

Passing a state variable to parent view

I have the following code:
struct BookView: View {
#State var title = ""
#State var author = ""
var body: some View {
TextField("Title", text: $title)
TextField("Author", text: $author)
}
}
struct MainView: View {
#State private var presentNewBook: Bool = false
var body: some View {
NavigationView {
// ... some button that toggles presentNewBook
}.sheet(isPresented: $presentNewBook) {
let view = BookView()
view.toolbar {
ToolbarItem(placement: principal) {
TextField("Title", text: view.$title)
}
}
}
}
}
This compiles but is giving me the following error on runtime:
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.
How do I pass a state variable to some other outside view? I can't use ObservableObject on BookView since that would require me to change it from struct to class
In general, your state should always be owned higher up the view hierarchy. Trying to access the child state from a parent is an anti-pattern.
One option is to use #Bindings to pass the values down to child views:
struct BookView: View {
#Binding var title : String
#Binding var author : String
var body: some View {
TextField("Title", text: $title)
TextField("Author", text: $author)
}
}
struct ContentView: View {
#State private var presentNewBook: Bool = false
#State private var title = ""
#State private var author = ""
var body: some View {
NavigationView {
VStack {
Text("Title: \(title)")
Text("Author: \(author)")
Button("Open") {
presentNewBook = true
}
}
}.sheet(isPresented: $presentNewBook) {
BookView(title: $title, author: $author)
}
}
}
Another possibility is using an ObservableObject:
class BookState : ObservableObject {
#Published var title = ""
#Published var author = ""
}
struct BookView: View {
#ObservedObject var bookState : BookState
var body: some View {
TextField("Title", text: $bookState.title)
TextField("Author", text: $bookState.author)
}
}
struct ContentView: View {
#State private var presentNewBook: Bool = false
#StateObject private var bookState = BookState()
var body: some View {
NavigationView {
VStack {
Text("Title: \(bookState.title)")
Text("Author: \(bookState.author)")
Button("Open") {
presentNewBook = true
}
}
}.sheet(isPresented: $presentNewBook) {
BookView(bookState: bookState)
}
}
}
I've altered your example views a bit because to me the structure was unclear, but the concept of owning the state at the parent level is the important element.
You can also pass a state variable among views as such:
let view = BookView(title: "foobar")
view.toolbar {
ToolbarItem(placement: principal) {
TextField("Title", text: view.$title)
}
}
Then, inside of BookView:
#State var title: String
init(title: String) {
_title = State(initialValue: title)
}
Source: How could I initialize the #State variable in the init function in SwiftUI?

Trouble passing data between views using EnvironmentObject in SwiftUI

I'm having trouble passing data through different views with EnvironmentObject. I have a file called LineupDetails that contains the following:
import SwiftUI
class TeamDetails: ObservableObject {
let characterLimit = 3
#Published var TeamName: String = "" {
didSet {
if TeamName.count > characterLimit {
TeamName = String(TeamName.prefix(characterLimit))
}
}
}
#Published var TeamColor: Color = .blue
#Published var hitter1First: String = ""
#Published var hitter1Last: String = ""
#Published var hitter2First: String = ""
#Published var hitter2Last: String = ""
#Published var hitter3First: String = ""
#Published var hitter3Last: String = ""
#Published var hitter4First: String = ""
#Published var hitter4Last: String = ""
#Published var hitter5First: String = ""
#Published var hitter5Last: String = ""
#Published var hitter6First: String = ""
#Published var hitter6Last: String = ""
#Published var hitter7First: String = ""
#Published var hitter7Last: String = ""
#Published var hitter8First: String = ""
#Published var hitter8Last: String = ""
#Published var hitter9First: String = ""
#Published var hitter9Last: String = ""
#Published var Hitter1Pos = "P"
#Published var Hitter2Pos = "C"
#Published var Hitter3Pos = "1B"
#Published var Hitter4Pos = "2B"
#Published var Hitter5Pos = "3B"
#Published var Hitter6Pos = "SS"
#Published var Hitter7Pos = "LF"
#Published var Hitter8Pos = "CF"
#Published var Hitter9Pos = "RF"
}
These variables are edited through a form in SetHomeLineup. I have excluded the parts of the view not related to the problem, marking them with ...:
struct SetHomeLineup: View {
#EnvironmentObject var HomeTeam: TeamDetails
...
var body: some View {
HStack {
TextField("Name", text: $HomeTeam.hitter1First)
TextField("Last Name", text: $HomeTeam.hitter1Last)
Picker(selection: $HomeTeam.Hitter1Pos, label: Text("")) {
ForEach(positions, id: \.self) {
Text($0)
}
}
}
HStack {
TextField("Name", text: $HomeTeam.hitter2First)
TextField("Last Name", text: $HomeTeam.hitter2Last)
Picker(selection: $HomeTeam.Hitter2Pos, label: Text("")) {
ForEach(positions, id: \.self) {
Text($0)
}
}
}
...
}
// and textfields so on until Hitter9, first and last
Now, when I try to include the inputted values of the above text fields to a different view, with code like this, the view always appears empty to match the default value of the string.
struct GameView: View {
#EnvironmentObject var HomeTeam: TeamDetails
...
var body: some View {
Text(HomeTeam.hitter1First)
}
}
Can someone tell me what I'm doing wrong? I tried using a similar code in a fresh project and it seemed to work just fine, so I'm stumped.
EDIT:
My views are instantiated like so:
The first view of the app is the SetAwayLineup, which includes a NavigationLink to SetHomeLineup like so.
var details = TeamDetails()
NavigationLink(destination: SetHomeLineup().environmentObject(details), isActive: self.$lineupIsReady) {
Similarly, SetHomeLineup includes a navigation link to GameView like so
var details = TeamDetails()
NavigationLink(destination: GameView().environmentObject(details), isActive: self.$lineupIsReady) {
Both screens have an EnvironmentObject of AwayLineup and HomeLineup that I'm trying to call into GameView.
Hopefully this simplifies it
The trunk is injected in the NavigationView and doesn't need to be re-injected. Even if one of the children doesn't use it. Truck belongs to the NavigationView
Then I have created 2 branches A and B that have their own Objects A cannot see Bs and vicecersa.
Each branch has access to their object and the sub-branches (NavigationLink) can be connected to the branch's object by injecting it.
import SwiftUI
struct TreeView: View {
#StateObject var trunk: Trunk = Trunk()
var body: some View {
NavigationView{
List{
NavigationLink(
destination: BranchAView(),
label: {
Text("BranchA")
})
NavigationLink(
destination: BranchBView(),
label: {
Text("BranchB")
})
}.navigationTitle("Trunk")
}
//Available to all items in the NavigationView
//With no need to re-inject for all items of the navView
.environmentObject(trunk)
}
}
///Has no access to BranchB
struct BranchAView: View {
#StateObject var branchA: BranchA = BranchA()
#EnvironmentObject var trunk: Trunk
var body: some View {
VStack{
Text(trunk.title)
Text(branchA.title)
NavigationLink(
destination: BranchAAView()
//Initial injection
.environmentObject(branchA)
,
label: {
Text("Go to Branch AA")
})
}.navigationTitle("BranchA")
}
}
//Has no access to BranchA
struct BranchBView: View {
#StateObject var branchB: BranchB = BranchB()
#EnvironmentObject var trunk: Trunk
var body: some View {
VStack{
Text(trunk.title)
Text(branchB.title)
NavigationLink(
destination: BranchBBView()
//Initial injection
.environmentObject(branchB),
label: {
Text("Go to Branch BB")
})
}.navigationTitle("BranchB")
}
}
struct BranchAAView: View {
#EnvironmentObject var branchA: BranchA
#EnvironmentObject var trunk: Trunk
var body: some View {
VStack{
Text(trunk.title)
Text(branchA.title)
NavigationLink(
destination: BranchAAAView()
//Needs re-injection because it is a NavigationLink sub-branch
.environmentObject(branchA)
,
label: {
Text("Go to AAA")
})
}.navigationTitle("BranchAA")
}
}
struct BranchAAAView: View {
#EnvironmentObject var branchA: BranchA
#EnvironmentObject var trunk: Trunk
var body: some View {
VStack{
Text(trunk.title)
Text(branchA.title)
}.navigationTitle("BranchAAA")
}
}
struct BranchBBView: View {
var body: some View {
VStack{
Text("I don't need to use the trunk or branch BB")
//No need to re-inject it is the same branch
BranchBBBView()
}.navigationTitle("BranchBB")
}
}
struct BranchBBBView: View {
#EnvironmentObject var branchB: BranchB
#EnvironmentObject var trunk: Trunk
var body: some View {
VStack{
Text("BranchBBBView").font(.title).fontWeight(.bold)
Text(trunk.title)
Text(branchB.title)
}.navigationTitle("BranchBB & BranchBBB")
}
}
struct TreeView_Previews: PreviewProvider {
static var previews: some View {
TreeView()
}
}
class Trunk: ObservableObject {
var title: String = "Trunk"
}
class BranchA: ObservableObject {
var title: String = "BranchA"
}
class BranchB: ObservableObject {
var title: String = "BranchB"
}
You need to make sure that you're passing the same environment object to any views that need to share the same data. That means you should create the object and store it in a variable so that you can pass it to both views. From your comments you have:
NavigationLink(destination: GameView(testUIView:
sampleGameViews[0]).environmentObject(TeamDetails()),
isActive: self.$lineupIsReady { ...
That TeamDetails() constructs a new instance of the TeamDetails class, one that you haven't stored. That means you must also be doing the same for your SetHomeLineup view. Instead, you'll need to create a single instance and keep a reference to it, then pass that reference to any views that you want to share the same data:
var details = TeamDetails()
that should be the only place where you use TeamDetails(); use details when you're setting up your GameView and SetHomeLineup views.
Update: Given your edit, the problem is again clear. You're still instantiating the TeamDetails class twice, so that the two views still get their own separate instances of that class. They need to use the same instance if they're to share information. So there should be only one var details = TeamDetails() line, and the resulting details variable should be used as the environmentObject for both views.
For example, instead of:
var details = TeamDetails()
NavigationLink(destination: SetHomeLineup().environmentObject(details), isActive: self.$lineupIsReady) {...
//...
var details = TeamDetails()
NavigationLink(destination: GameView().environmentObject(details), isActive: self.$lineupIsReady) {
you want:
var details = TeamDetails()
NavigationLink(destination: SetHomeLineup().environmentObject(details), isActive: self.$lineupIsReady) {...
NavigationLink(destination: GameView().environmentObject(details), isActive: self.$lineupIsReady) {
In general, make sure that you have a clear understanding of the difference between reference types and value types, and between a class and an instance of that class. If Mazda Miata is a class, and if I buy a Miata, then the specific car that I've is an instance of the class. If I ask you to wash my car, and I ask someone else to change the oil in my car, I'll end up with one car that's clean and has new oil. What's going on in your code is that you're buying a Miata and asking someone to wash it, and buying another car and asking someone to change the oil. They're two different cars, so they have different states.

How do I change the bool value of an item that comes from a struct and hence update a checklist?

Background
I am trying to build a list with a checkmark/tick box next to it. A struct is used to create the "data" for each item. This is then passed on to a class which holds an array of the items created by the struct. From here I used the observable object protocol and passed the class into a list.
Objective
I would like to be able to individually mark each item as completed when it is done.
Current Analysis
I know the image switches when I manually change the 'completed' value from false to true.
I also tested the onTapAction just to be sure it is working.
I think the problem lies in "self.one.completed.toggle()" or the binding or something I am unaware of.
struct One: Identifiable, Codable {
let id = UUID()
var item: String
var completed:Bool = false
}
class OneList: ObservableObject{
#Published var items1 = [One]()
struct ContentView: View {
#ObservedObject var itemss1 = OneList()
#ObservedObject var itemss2 = TwoList()
#ObservedObject var itemss3 = ThreeList()
#ObservedObject var itemss4 = FourList()
#State private var showingAdditem: Bool = false
#Binding var one:One
var body: some View {
NavigationView{
ZStack{
List{
Section(header: Text("Vital")){
ForEach(itemss1.items1){ item in
HStack{
Image(systemName: self.one.completed ? "checkmark.circle":"circle")
.onTapGesture {
self.one.completed.toggle()
}
Text(item.item)}
P.S. I am relatively new to Swift and Stack overflow so any other suggestions would be appreciated
In my other answer I achieved something like this with ObservableObject protocol for needed object and then playing with EnvironmentObject. Actually I didn't try to do this with other wrappers. Here is the code, where you can see switching images:
import SwiftUI
class One: Identifiable, ObservableObject { // ObservableObject requires class
let id: UUID
var item: String = "[undefined]"
#Published var completed: Bool = false // this will affect the UI
init(item: String, completed: Bool) {
id = UUID()
self.item = item
self.completed = completed
}
}
class OneList: ObservableObject{
#Published var items = [One(item: "first", completed: false),
One(item: "second", completed: false),
One(item: "third", completed: false)]
}
struct CheckboxList: View {
#EnvironmentObject var itemList: OneList
var body: some View {
List {
Section(header: Text("Vital")) {
ForEach(itemList.items.indices) { index in
VitalRow()
.environmentObject(self.itemList.items[index])
.onTapGesture {
self.itemList.items[index].completed.toggle()
}
}
}
}
}
}
struct VitalRow: View {
#EnvironmentObject var item: One
var body: some View {
HStack{
Image(systemName: item.completed ? "checkmark.circle" : "circle")
Text("\(item.item)")
}
}
}
struct CheckboxList_Previews: PreviewProvider {
static var previews: some View {
CheckboxList().environmentObject(OneList())
}
}