I have a model which, for the sake of example, is a tag cloud and a model for items:
struct TagCloud: Identifiable, Hashable{
var id: Int
let tag: String
static func tagCloud() -> [TagCloud]{
return [ TagCloud(id: 01, tag:"Green"),
TagCloud(id: 02, tag:"Blue"),
TagCloud(id: 03, tag:"Red")]
}
}
struct TaggedItem: Identifiable, Hashable{
var id: Int
let tag: String
let item: String
static func taggedItems() -> [TaggedItem]{
return [ TaggedItem(id: 01, tag:"Green", item: "Tree"),
TaggedItem(id: 02, tag:"Blue", item: "Sky"),
TaggedItem(id: 03, tag:"Red", item: "Apple")...]
}
}
I have a class to 'contain' the currently selected items:
class SelectedItems: ObservableObject {
#Published var currentlySelectedItems:[TaggedItem] = []
func changeData(forTag tag: String ){
let currentSelection = TaggedItem. taggedItems()
let filteredList = cardCollection.filter { $0.tag == tag }
currentlySelectedItems = filteredList
}
}
In my parent view, I select one of the tags from the cloud:
struct ParentView: View {
let tagCloud = TagCloud.tagCloud()
#ObservedObject var currentSelection : TaggedItem = TaggedItem()
#State var navigationTag:Int? = nil
var body: some View {
NavigationLink(destination: ChildView(), tag: 1, selection: $tag) {
EmptyView()
}
VStack{
ScrollView(.horizontal, content: {
HStack(spacing: 20){
ForEach( self.tagCloud, id: \.self) { item in
VStack{
Button(action: {
self. currentSelection.changeData(forTag: item.tag )
self.navigationTag = 1
}){
Text(item.tag)
}.buttonStyle(PlainButtonStyle())
..
}
The child view contains the ObservedObject. As a side note, I have also set this as an EnvironmentObject.
struct ChildView: View {
#ObservedObject var currentItems : SelectedItems = SelectedItems()
var body: some View {
VStack{
ScrollView(.horizontal, content: {
HStack(spacing: 20){
ForEach( currentItems.currentlySelectedItems, id: \.self) { item in
...
The problem:
In the parent view, the button calls SelectedItems in order to create a filtered list of items that match the selected tag
The call is made and the list is set (verified by print)
However, the data never "reaches" the child view
I tried a number of things with init(). I tried passing the selected tag to the child, and then doing the filtering within init() itself, but was stymied by the need to bind to a class. I read elsewhere to try having a second model which would be updated by the FIRST model in order to trigger a view refresh.
What is the correct way to create this filtered list via a parent view selection and make the list available in the child view?
This part should be rethink:
let tagCloud = TagCloud.tagCloud()
#ObservedObject var currentSelection : TaggedItem = TaggedItem()
^^ is a struct, it cannot be observed !!!
#ObservedObject must be applied only to #ObservableObject as you did for SelectedItems, so probably another ObservableObject view model wrapper around TaggedItem is expected here.
Related
When I update a binding property from an array in a pushed view 2+ layers down, the navigation pops back instantly after a change to the property.
Xcode 13.3 beta, iOS 15.
I created a simple demo and code is below.
Shopping Lists
List Edit
List section Edit
Updating the list title (one view deep) is fine, navigation stack stays same, and changes are published if I return. But when adjusting a section title (two deep) the navigation pops back as soon as I make a single change to the property.
I have a feeling I'm missing basic fundamentals here, and I have a feeling it must be related to the lists id? but I'm struggling to figure it out or work around it.
GIF
Code:
Models:
struct ShoppingList {
let id: String = UUID().uuidString
var title: String
var sections: [ShoppingListSection]
}
struct ShoppingListSection {
let id: String = UUID().uuidString
var title: String
}
View Model:
final class ShoppingListsViewModel: ObservableObject {
#Published var shoppingLists: [ShoppingList] = [
.init(
title: "Shopping List 01",
sections: [
.init(title: "Fresh food")
]
)
]
}
Content View:
struct ContentView: View {
var body: some View {
NavigationView {
ShoppingListsView()
}
}
}
ShoppingListsView
struct ShoppingListsView: View {
#StateObject private var viewModel = ShoppingListsViewModel()
var body: some View {
List($viewModel.shoppingLists, id: \.id) { $shoppingList in
NavigationLink(destination: ShoppingListEditView(shoppingList: $shoppingList)) {
Text(shoppingList.title)
}
}
.navigationBarTitle("Shopping Lists")
}
}
ShoppingListEditView
struct ShoppingListEditView: View {
#Binding var shoppingList: ShoppingList
var body: some View {
Form {
Section(header: Text("Title")) {
TextField("Title", text: $shoppingList.title)
}
Section(header: Text("Sections")) {
List($shoppingList.sections, id: \.id) { $section in
NavigationLink(destination: ShoppingListSectionEditView(section: $section)) {
Text(section.title)
}
}
}
}
.navigationBarTitle("Edit list")
}
}
ShoppingListSectionEditView
struct ShoppingListSectionEditView: View {
#Binding var section: ShoppingListSection
var body: some View {
Form {
Section(header: Text("Title")) {
TextField("title", text: $section.title)
}
}
.navigationBarTitle("Edit section")
}
}
try this, works for me:
struct ContentView: View {
var body: some View {
NavigationView {
ShoppingListsView()
}.navigationViewStyle(.stack) // <--- here
}
}
Try to make you object confirm to Identifiable and return value which unique and stable, for your case is ShoppingList.
Detail view seems will pop when object id changed.
The reason your stack is popping back to the root ShoppingListsView is that the change in the list is published and the root ShoppingListsView is registered to listen for updates to the #StateObject.
Therefore, any change to the list is listened to by ShoppingListsView, causing that view to be re-rendered and for all new views on the stack to be popped in order to render the root ShoppingListsView, which is listening for updates on the #StateObject.
The solution to this is to change the #StateObject to #EnvironmentObject
Please refactor your code to change ShoppingListsViewModel to use an #EnvironmentObject wrapper instead of a #StateObject wrapper
You may pass the environment object in to all your child views and also add a boolean #Published flag to track any updates to the data.
Then your ShoppingListView would look as below
struct ShoppingListsView: View {
#EnvironmentObject var viewModel = ShoppingListsViewModel()
var body: some View {
List($viewModel.shoppingLists, id: \.id) { $shoppingList in
NavigationLink(destination: ShoppingListEditView(shoppingList: $shoppingList)) {
Text(shoppingList.title)
}
}
.navigationBarTitle("Shopping Lists")
}
}
Don't forget to pass the viewModel in to all your child views.
That should fix your problem.
I have a list of sliders, but I have a problem updating the text that shows the slider value.
The app workflow is like this:
User taps to add a new slider to the list.
An object that defines the slider is created and stored in an array.
The class that has the array as a property (Db) is an ObservableObject and triggers a View update for each new item.
The list is updated with a new row.
So far, so good. Each row has a slider whose value is stored in a property in an object in an array. However, the value text doesn't update as soon as the slider is moved, but when a new item is added. Please see the GIF below:
The Slider doesn't update the text value when moved
How can I bind the slider movements to the text value? I thought that by defining
#ObservedObject var slider_value: SliderVal = SliderVal()
and binding that variable to the slider, the value would be updated simultaneously but that is not the case. Thanks a lot for any help.
import SwiftUI
import Combine
struct ContentView: View {
#ObservedObject var db: Db
var body: some View {
NavigationView{
List(db.criteria_db){criteria in
VStack {
HStack{
Text(criteria.name).bold()
Spacer()
Text(String(criteria.slider_value.value)) //<-- Problem here
}
Slider(value: criteria.$slider_value.value, in:0...100, step: 1)
}
}
.navigationBarTitle("Criteria")
.navigationBarItems(trailing:
Button(action: {
Criteria.count += 1
db.criteria_db.append(Criteria(name: "Criteria\(Criteria.count)"))
dump(db.criteria_db)
}, label: {
Text("Add Criteria")
})
)
}
.listStyle(InsetGroupedListStyle())
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView(db: Db())
}
}
struct Criteria: Identifiable {
var id = UUID()
var name: String
#ObservedObject var slider_value: SliderVal = SliderVal()
static var count: Int = 0
init(name: String) {
self.name = name
}
}
class Db: ObservableObject {
#Published var criteria_db: [Criteria] = []
}
class SliderVal: ObservableObject {
#Published var value:Double = 50
}
The #ObservableObject won't work within a struct like that -- it's only useful inside a SwiftUI View or a DynamicProperty. With your use case, because the class is a reference type, the #Published property has no way of knowing that the SliderVal was changed, so the owner View never gets updated.
You can fix this by turning your model into a struct:
struct Criteria: Identifiable {
var id = UUID()
var name: String
var slider_value: SliderVal = SliderVal()
static var count: Int = 0
init(name: String) {
self.name = name
}
}
struct SliderVal {
var value:Double = 50
}
The problem, once you do this, is you don't have a Binding to use in your List. If you're lucky enough to be on SwiftUI 3.0 (iOS 15 or macOS 12), you can use $criteria within your list to get a binding to the element being currently iterated over.
If you're on an earlier version, you'll need to either use indexes to iterate over the items, or, my favorite, create a custom binding that is tied to the id of the item. It looks like this:
struct ContentView: View {
#ObservedObject var db: Db = Db()
private func bindingForId(id: UUID) -> Binding<Criteria> {
.init {
db.criteria_db.first { $0.id == id } ?? Criteria(name: "")
} set: { newValue in
db.criteria_db = db.criteria_db.map {
$0.id == id ? newValue : $0
}
}
}
var body: some View {
NavigationView{
List(db.criteria_db){criteria in
VStack {
HStack{
Text(criteria.name).bold()
Spacer()
Text(String(criteria.slider_value.value))
}
Slider(value: bindingForId(id: criteria.id).slider_value.value, in:0...100, step: 1)
}
}
.navigationBarTitle("Criteria")
.navigationBarItems(trailing:
Button(action: {
Criteria.count += 1
db.criteria_db.append(Criteria(name: "Criteria\(Criteria.count)"))
dump(db.criteria_db)
}, label: {
Text("Add Criteria")
})
)
}
.listStyle(InsetGroupedListStyle())
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView(db: Db())
}
}
class Db: ObservableObject {
#Published var criteria_db: [Criteria] = []
}
Now, because the models are all value types (structs), the View and #Published know when to update and your sliders work as expected.
try something like this:
Slider(value: criteria.$slider_value.value, in:0...100, step: 1)
.onChange(of: criteria.slider_value.value) { newVal in
DispatchQueue.main.async {
criteria.slider_value.value = newVal
}
}
I have a Class "ActualCourse"
class ActualCourse : ObservableObject {
#Published var id : UUID?
#Published var CourseName : String = ""
}
And two Structs "Settings" and "Course"
struct Settings: View {
#State private var action : Int? = 0
#ObservedObject var objCourse = ActualCourse()
#State var courseId : UUID = UUID()
#State var list : [Course] = [] // list is not empty, I didn't show it to you to make the code lighter
init() {
objCourse.id = UUID()
}
var body: some View {
NavigationView{
VStack{
NavigationLink(destination: Course(), tag: 1, selection: $action){}
List {
let count = list.count
ForEach(0 ..< count, id: \.self){ index in
HStack {
Image(systemName: "chevron.right.circle.fill")
.font(.title)
.onTapGesture {
objCourse.id = list[index].id
objCourse.nomCourse = list[index].nomCourse
print(objCourse.id!) // Id Appear when I click !
self.action = 1
}
But when I navigate to Course view, objCourse.id return nil
struct Settings: View {
#ObservedObject var objCourse = CourseActuelle()
....
.onAppear(){
print(self.objCourse.id!) // RETURN nil
}
What am I doing wrong ? I have to give a random UUID at the beginning because I can't find how to do in another way...
The CourseActuelle you're creating in the second view is independent of the one you're creating in the first view of which you're initializing the id value. If you want them to be the same you could use #EnvironmentObject in the second view and inject it in the first view or pass it in some other way.
I refer to two questions that I already asked and have been answered very well by Asperi: SwiftUI ForEach with .indices() does not update after onDelete,
SwiftUI onDelete List with Toggle
Now I tried to modify the closure in ForEach with a NavigationLink and suddenly the App crashes again with
Thread 1: Fatal error: Index out of range
when I try to swipe-delete.
Code:
class Model: ObservableObject {
#Published var name: String
#Published var items: [Item]
init(name: String, items: [Item]) {
self.name = name
self.items = items
}
}
struct Item: Identifiable {
var id = UUID()
var isOn: Bool
}
struct ContentView: View {
#EnvironmentObject var model: Model
var body: some View {
NavigationView {
List {
ForEach(model.items) {item in
NavigationLink(destination: DetailView(item: self.makeBinding(id: item.id))) {
Toggle(isOn: self.makeBinding(id: item.id).isOn)
{Text("Toggle-Text")}
}
}.onDelete(perform: delete)
}
}
}
func delete(at offsets: IndexSet) {
self.model.items.remove(atOffsets: offsets)
}
func makeBinding(id: UUID) -> Binding<Item> {
guard let index = self.model.items.firstIndex(where: {$0.id == id}) else {
fatalError("This person does not exist")
}
return Binding(get: {self.model.items[index]}, set: {self.model.items[index] = $0})
}
}
struct DetailView: View {
#Binding var item: Item
var body: some View {
Toggle(isOn: $item.isOn) {
Text("Toggle-Text")
}
}
}
It works without NavigationLink OR without the Toggle. So it seems for me that I only can use the makeBinding-Function once in this closure.
Thanks for help
Your code was crashing for me with and even without Navigation Link. Sometimes only if I deleted the last object in the Array. It looks like it was still trying to access an index out of the array. The difference to your example you linked above, is that they didn't used EnvironmentObject to access the array. The stored the array directly in the #State.
I came up with a little different approach, by declaring Item as ObservedObject and then simply pass it to the subview where you can use their values as Binding, without any function.
I changed Item to..
class Item: ObservableObject {
var id = UUID()
var isOn: Bool
init(id: UUID, isOn: Bool)
{
self.id = id
self.isOn = isOn
}
}
Change the ContentView to this..
struct ContentView: View {
#EnvironmentObject var model: Model
var body: some View {
NavigationView {
List {
ForEach(model.items, id:\.id) {item in
NavigationLink(destination: DetailView(item: item)) {
Toggler(item: item)
}
}.onDelete(perform: delete)
}
}
}
I outsourced the Toggle to a different view, where we pass the ObservedObject to, same for the DetailView.
struct Toggler: View {
#ObservedObject var item : Item
var body : some View
{
Toggle(isOn: $item.isOn)
{Text("Toggle-Text")}
}
}
struct DetailView: View {
#ObservedObject var item: Item
var body: some View {
Toggle(isOn: $item.isOn) {
Text("Toggle-Text")
}
}
}
They both take an Item as ObservedObject and use it as Binding for the Toggle.
I want to pop a NavigationLink from within code. I followed this article and it works for one link (https://swiftui-lab.com/bug-navigationlink-isactive/). However, when using a list of links, one has to use a separate boolean for each NavigationLink.
So I thought the smart way to do this is with an EnvironmentObject that holds a dictionary with a boolean for each ChildView:
class Navigation: ObservableObject{
#Published var show:[UUID:Bool] = [:]
}
Let's say we want to have a variable number child views (of type MyObject).
What needs to be changed in order to make it work?
struct MyObject:Identifiable{
var id = UUID()
var name:String
}
struct ContentView: View {
#EnvironmentObject var navigation:Navigation
var objects = [MyObject(name: "view1"), MyObject(name: "view2"), MyObject(name: "view3")]
init() {
for object in objects{
self.navigation.show[object.id] = false
}
}
var body: some View {
NavigationView{
VStack{
ForEach(objects, id:\.self.id){ object in
NavigationLink(destination: Child(object:object), isActive: self.$navigation.show[object.id], label: {
Text(object.name)
})
}
}
}
}
}
struct Child: View {
#EnvironmentObject var navi:Navigation
var object:MyObject
var body: some View {
Button(action:{self.navi.show[self.object.id] = false}, label: {
Text("back")
})
}
}
The view that the NavigationLink navigates to has an environment variable set called presentationMode. This variable lets you programatically pop your child view back to the parent view.
So instead of having to keep track of all the display states, we can simplify your Child struct to something like this:
struct Child: View {
#Environment(\.presentationMode) private var presentation
var object:MyObject
var body: some View {
Button(action:{ self.presentation.wrappedValue.dismiss() }, label: {
Text("back")
})
}
}