Swift - Update List from different View - ios

I have 2 Views in my Swift Project and when I click on the Button on the secondView, I want to update the List in the First View. I don't know how to do it! If I use a static variable in my MainView and then edit this variable from the secondView, it works, but it won't update. And if I don't use static and instead use #State, it would update, but I can't access it from my secondView.
Here is the Code below:
import SwiftUI
struct ContentView: View {
var body: some View {
TabView {
MainView()
.tabItem() {
VStack {
Image(systemName: "circle.fill")
Text("MainView")
}
}.tag(0)
UpdateOtherViewFromHere()
.tabItem() {
VStack {
Image(systemName: "circle.fill")
Text("SecondView")
}
}.tag(1)
}
}
}
struct MainView: View {
var arrayList: [CreateListItems] = []
init() {
let a = CreateListItems(name: "First Name!")
let b = CreateListItems(name: "Second Name!")
let c = CreateListItems(name: "Third Name!")
arrayList.append(a)
arrayList.append(b)
arrayList.append(c)
}
var body: some View {
return VStack {
ZStack {
NavigationView {
List {
ForEach(arrayList) { x in
Text("\(x.name)")
}
}.navigationBarTitle("Main View")
}
}
}
}
}
struct UpdateOtherViewFromHere: View {
func updateList() {
//Code that should remove "FirstName" from the List in MainView
}
var body: some View {
return VStack {
Button(action: {
updateList()
}) {
Image(systemName: "heart.slash")
.font(.largeTitle)
Text("Click Me!")
}
}
}
}
struct CreateListItems: Identifiable {
var id: UUID = UUID()
var name: String
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}

You can share it using #State and #Binding if you put
struct ContentView: View {
#State var arrayList: [CreateListItems] = []
struct MainView: View {
#Binding var arrayList: [CreateListItems]
struct UpdateOtherViewFromHere: View {
#Binding var arrayList: [CreateListItems]
or you use the MVVM pattern and store the list in an ObservableObject and use #StateObject/#ObservedObject (source) and use #EnvironmentObject(connection) to share it between your Views.
https://developer.apple.com/documentation/swiftui/managing-model-data-in-your-app
class ParentViewModel: ObservableObject{
#Published var arrayList: [CreateListItems] = []
init(){
addSamples()
}
func addSamples() {
let a = CreateListItems(name: "First Name!")
let b = CreateListItems(name: "Second Name!")
let c = CreateListItems(name: "Third Name!")
arrayList.append(a)
arrayList.append(b)
arrayList.append(c)
}
func updateList() {
let a = CreateListItems(name: "\(arrayList.count + 1) Name!")
arrayList.append(a)
}
}
struct ParentView: View {
#StateObject var vm: ParentViewModel = ParentViewModel()
var body: some View {
TabView {
MainView().environmentObject(vm)
.tabItem() {
VStack {
Image(systemName: "circle.fill")
Text("MainView")
}
}.tag(0)
UpdateOtherViewFromHere().environmentObject(vm)
.tabItem() {
VStack {
Image(systemName: "circle.fill")
Text("SecondView")
}
}.tag(1)
}
}
}
struct MainView: View {
#EnvironmentObject var vm: ParentViewModel
var body: some View {
return VStack {
ZStack {
NavigationView {
List {
ForEach(vm.arrayList) { x in
Text(x.name)
}
}.navigationBarTitle("Main View")
}
}
}
}
}
struct UpdateOtherViewFromHere: View {
#EnvironmentObject var vm: ParentViewModel
var body: some View {
return VStack {
Button(action: {
vm.updateList()
}) {
Image(systemName: "heart.slash")
.font(.largeTitle)
Text("Click Me!")
}
}
}
}

Related

EmptyBody().onAppear not works when sheet present with item

When I present sheet with .sheet(isPresented... onAppear of EmptyView() triggered
but when I use .sheet(item... then onAppear doesn't trigger. I don't understand what mistake I am doing?
item:
enum ActiveSheet: Identifiable {
var id: String { UUID().uuidString }
case customA
case customB
}
Main View:
struct ContentView: View {
#State private var activeSheet: ActiveSheet?
var body: some View {
VStack {
Button(action: { activeSheet = .customA }) {
Text("View A")
}
Button(action: { activeSheet = .customB }) {
Text("View B")
}
}
.buttonStyle(.borderedProminent)
//If I use this .sheet(isPresented... then onAppear triggers, but not with item
.sheet(item: $activeSheet) { item in
switch item {
case .customA:
CustomViewA()
case .customB:
CustomViewB()
}
}
}
}
Empty Views:
struct CustomViewA: View {
var body: some View {
EmptyView()
.onAppear {
print("OnAppear")
}
}
}
struct CustomViewB: View {
var body: some View {
EmptyView()
.onAppear {
print("OnAppear")
}
}
}

NavigationStack pushing new View issue with #Published

Weird issue using new NavigationStack. When trying to push the DrinkView for the second time, it's pushed twice and the OrderFood gets view removed from the navigation.
The reason is #Published var openDrinks in the View Model. Is there is any way to solve this issue.
Thanks.
import SwiftUI
struct ContentView: View {
var body: some View {
NavigationStack {
VStack {
Image(systemName: "globe")
.imageScale(.large)
.foregroundColor(.accentColor)
NavigationLink("Hello", value: "Amr")
// Text("Hello, world!")
}
.navigationTitle("Main")
.padding()
.navigationDestination(for: String.self) { value in
OrderFood(viewModel: ViewModel())
}
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
class ViewModel: ObservableObject {
#Published var openDrinks: Bool = false
}
struct OrderFood: View {
#ObservedObject var viewModel: ViewModel
// #ObservedObject var viewModel = ViewModel()
var body: some View {
VStack {
Text("Add Drink")
.onTapGesture {
viewModel.openDrinks = true
}
}
.navigationTitle("Order Food")
.navigationDestination(isPresented: $viewModel.openDrinks) {
DrinksView()
.navigationTitle("Drinks")
}
.onAppear {
viewModel.openDrinks = false
}
}
}
struct OrderFood_Previews: PreviewProvider {
static var previews: some View {
OrderFood(viewModel: ViewModel())
}
}
import SwiftUI
struct DrinksView: View {
var body: some View {
NavigationLink("Ch") {
Text("Hello, World!")
}
}
}
struct DrinksView_Previews: PreviewProvider {
static var previews: some View {
DrinksView()
}
}
In ContentView, you use OrderFood(viewModel: ViewModel()), which means
you create a new ViewModel every time you navigate to OrderFood.
Try this approach, where you have one source of truth, that you pass to the details view:
struct ContentView: View {
#StateObject var viewModel = ViewModel() // <-- here
var body: some View {
NavigationStack {
VStack {
Image(systemName: "globe")
.imageScale(.large)
.foregroundColor(.accentColor)
NavigationLink("Hello", value: "Amr")
}
.navigationTitle("Main")
.padding()
.navigationDestination(for: String.self) { value in
OrderFood(viewModel: viewModel) // <-- here
}
}
}
}
Note, you could also use #EnvironmentObject in this case.
EDIT-1: using #EnvironmentObject to pass the viewModel around:
struct ContentView: View {
#StateObject var viewModel = ViewModel() // <-- here
var body: some View {
NavigationStack {
VStack {
Image(systemName: "globe")
.imageScale(.large)
.foregroundColor(.accentColor)
NavigationLink("Hello", value: "Amr")
}
.navigationTitle("Main")
.padding()
.navigationDestination(for: String.self) { value in
OrderFood() // <-- here
}
}.environmentObject(viewModel) // <-- here
}
}
struct OrderFood: View {
#EnvironmentObject var viewModel: ViewModel // <-- here
var body: some View {
VStack {
Text("Add Drink")
.onTapGesture {
viewModel.openDrinks = true
}
}
.navigationTitle("Order Food")
.navigationDestination(isPresented: $viewModel.openDrinks) {
DrinksView().navigationTitle("Drinks")
}
.onAppear {
viewModel.openDrinks = false
}
}
}

How to pass data between ViewModels in SwiftUI

I have this use case where I have a parent view and a child view. Both of the views have their own corresponding ViewModels.
ParentView:
struct ParentView: View {
#StateObject var parentViewModel = ParentViewModel()
var body: some View {
NavigationView {
List {
TextField("Add Name", text: $parentViewModel.newListName)
NavigationLink(destination: ChildView()) {
Label("Select Products", systemImage: K.ListIcons.productsNr)
}
}
}
}
ParentViewModel:
class ParentViewModel: ObservableObject {
#Published var newListName: String = ""
func saveList() {
// some logic to save to CoreData, method would be called via a button
// how do I reference "someString" from ChildViewModel in this ViewModel?
}
}
ChildView:
struct ChildView: View {
#StateObject var childViewModel = ChildViewModel()
var body: some View {
NavigationView {
List{
Text("Some element")
.onTapGesture {
childViewModel.alterData()
}
}
}
}
}
ChildViewModel:
class ChildViewModel: ObservableObject {
#Published var someString: String = ""
func alterData() {
someString = "Toast"
}
}
My question now is, how do I pass the new value of "someString" from ChildViewModel into the ParentViewModel, in order to do some further stuff with it?
I've tried to create a #StateObject var childViewModel = ChildViewModel() reference in the ParentViewModel, but that does obviously not work, as this will create a new instance of the ChildViewModel and therefore not know of the changes made to "someString"
Solution:
As proposed by Josh, I went with the approach to use a single ViewModel instead of two. To achieve this, the ParentView needs a .environmentObject(T) modifier.
ParentView:
struct ParentView: View {
#StateObject var parentViewModel = ParentViewModel()
var body: some View {
NavigationView {
List {
TextField("Add Name", text: $parentViewModel.newListName)
NavigationLink(destination: ChildView()) {
Label("Select Products", systemImage: K.ListIcons.productsNr)
}
}
}.environmentObject(parentViewModel)
}
The ChildView then references that environment Object via #EnvironmentObject without an initializer:
struct ChildView: View {
#EnvironmentObject var parentViewModel: ParentViewModel
var body: some View {
NavigationView {
List{
Text("Some element")
.onTapGesture {
parentViewModel.alterData()
}
}
}
}
}
Most likely you would use a binding for this situation:
struct ChildView: View {
#Binding var name: String
var body: some View {
NavigationView {
List{
Text("Some element")
.onTapGesture {
name = "Altered!"
}
}
}
}
}
And in the parent:
struct ParentView: View {
#StateObject var parentViewModel = ParentViewModel()
var body: some View {
NavigationView {
List {
TextField("Add Name", text: $parentViewModel.newListName)
NavigationLink(destination: ChildView(name: $parentViewModel.newListName)) {
Label("Select Products", systemImage: K.ListIcons.productsNr)
}
}
}
}
Also, I think you can remove the NavigationView view from ChildView. Having it ParentView is enough.

Updating EnvironmentObject in child view causes view to pop

I have a child view that updates an EnvironmentObject that then causes the child view to pop back to its parent view. I am creating an app that uses similar "Like" functionality from this tutorial: https://www.hackingwithswift.com/books/ios-swiftui/letting-the-user-mark-favorites
Every time the like button is clicked and the EnvironmentObject likes object is updated, the view pops to the previous (ProductGridView) view instead of staying on the child view (ProductDetailView).
struct ContentView: View {
#State private var tabSelection = 0
#ObservedObject var products = Products()
#ObservedObject var favorites = Favorites()
var body: some View {
VStack {
TabView(selection: $tabSelection) {
NavigationView{
ProductGridView()
}
.tabItem { Image(systemName: "megaphone")
Text("Products")
}.tag(0)
.environmentObject(products)
.environmentObject(favorites)
}
struct ProductGridView: View {
var columns: [GridItem] = Array(repeating: .init(.flexible()), count: 2)
#EnvironmentObject var products: Products
#EnvironmentObject var favorites: Favorites
var body: some View {
VStack{
ScrollView(.vertical, showsIndicators: false) {
LazyVGrid(columns: columns, alignment: .leading, spacing: 20) {
ForEach(products.products, content: {
product in
NavigationLink(destination: ProductDetailView(product: product)) {
ProductCellView(product: product)
.padding(.horizontal, 10)
}
})
}
}.onAppear() {
self.products.fetchData()
}
}
struct ProductDetailView: View {
let product: Product
#EnvironmentObject var favorites: Favorites
var body: some View {
ScrollView(showsIndicators: false) {
VStack{
ProductImageView(product: product)
Button(action: {
if favorites.contains(product) {
favorites.remove(product) //Updating here causes issue
} else {
favorites.add(product) //Updating here causes issue
}
}) {
if favorites.contains(product){
Image(systemName: "heart.fill")
}
else{
Image(systemName: "heart")
}
}
}
class Favorite : Identifiable, Encodable {
var id = UUID()
var name: String
...
class Favorites: ObservableObject {
#Published private var products: [String]?
...
struct Product: Identifiable{
let id = UUID()
let productname: String
...
It looks like your fetch data call may be causing the issue.
struct YourContentView: View {
#State private var tabSelection = 0
#ObservedObject var products = Products()
#ObservedObject var favorites = Favorites()
var body: some View {
VStack {
TabView(selection: $tabSelection) {
NavigationView{
ProductGridView()
}
.tabItem { Image(systemName: "megaphone")
Text("Products")
}.tag(0)
.environmentObject(products)
.environmentObject(favorites)
}
}
}
}
struct ProductDetailView: View {
let product: Product
#EnvironmentObject var favorites: Favorites
var body: some View {
ScrollView(showsIndicators: false) {
VStack{
Image(systemName: "photo")
.resizable()
.scaledToFit()
Button {
if favorites.products?.contains(product) ?? false {
favorites.remove(product) //Updating here causes issue
} else {
favorites.add(product) //Updating here causes issue
}
} label: {
if favorites.products?.contains(product) ?? false{
Image(systemName: "heart.fill")
}
else{
Image(systemName: "heart")
}
}
}
}
}
}
struct ProductCellView: View {
#State var product: Product
var body: some View {
HStack {
Image(systemName: "photo")
Text(product.productname)
}
}
}
struct ProductGridView: View {
let columns: [GridItem] = Array(repeating: .init(.flexible()), count: 2)
#EnvironmentObject var products: Products
#EnvironmentObject var favorites: Favorites
var body: some View {
VStack{
ScrollView(.vertical, showsIndicators: false) {
LazyVGrid(columns: columns, alignment: .leading, spacing: 20) {
ForEach(products.products, content: {
product in
NavigationLink(destination: ProductDetailView(product: product)) {
ProductCellView(product: product)
.padding(.horizontal, 10)
}
})
}
}.onAppear() {
self.products.fetchData()
}
}
}
}
class Favorites: ObservableObject {
#Published var products: [Product]? = []
init() {}
func remove(_ product: Product) {
products?.removeAll(where: { $0.id == product.id })
}
func add(_ product: Product) {
products?.append(product)
}
}
class Products: ObservableObject, Identifiable {
#Published var products: [Product]
init() {
products = [.init(productname: "ApplePie"), .init( productname: "Cheeseburger")]
}
func fetchData() {
// uncommenting this code will cause product grid view to reload because it relies on products
// products = [.init(productname: "ApplePie"), .init( productname: "Cheeseburger")]
}
}
struct Product: Identifiable, Equatable {
let id = UUID()
let productname: String
public static func ==(lhs: Product, rhs: Product) -> Bool {
lhs.id == rhs.id
}
}

swiftui subview reappear after click the back button and update state data

Very strange behavior.
Click the back button on the subpage (Subview) to return to the main page (ContentView). However, the subpage (Subview) automatically opens again. Why?
import SwiftUI
struct ContentView: View {
#State var things: [String] = []
#State var count: Int = 0
var body: some View {
NavigationView{
List {
ForEach(things.indices, id: \.self) { index in
Text(things[index])
}
}
.onAppear {
update()
}
.navigationTitle("a")
.toolbar{
NavigationLink(destination: Subview(count: $count), label: {
Text("sub")
})
}
}
}
func update() {
things = []
for i in 0...count {
things.append(String(i))
}
}
}
struct Subview: View {
var count : Binding<Int>
var body: some View {
Text("sub")
.onAppear {
count.wrappedValue += 1
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
NavigationLink should always be inside a NavigationView. If you put it in the toolbar or some other place, you might run into weird issues.
Instead, use the init(destination:isActive:label:) initializer. Then set the presentingNextPage property to true when you want to present the next page.
struct ContentView: View {
#State var things: [String] = []
#State var count: Int = 0
#State var presentingNextPage = false
var body: some View {
NavigationView {
List {
ForEach(things.indices, id: \.self) { index in
Text(things[index])
}
/// placeholder navigation link
NavigationLink(destination: Subview(count: $count), isActive: $presentingNextPage) {
EmptyView()
}
}
.onAppear {
self.update()
}
.navigationTitle("a")
.toolbar{
ToolbarItem(placement: .navigationBarTrailing) {
Button("sub") {
presentingNextPage = true /// set to true
}
}
}
}
}
func update() {
things = []
for i in 0...count {
things.append(String(i))
}
}
}
Result:
Put "onAppear{...}" on the NavigationView not the List, like this:
struct ContentView: View {
#State var things: [String] = []
#State var count: Int = 0
var body: some View {
NavigationView{
List {
ForEach(things.indices, id: \.self) { index in
Text(things[index])
}
}
.navigationTitle("a")
.toolbar{
NavigationLink(destination: Subview(count: $count), label: {
Text("sub")
})
}
}
.onAppear { // <---
update()
}
}

Resources