Swfitui Object not update when NavigationLink - swiftui

All
Something is wired when use swiftui.
object is not update in closure whick assign on second view when navigate back.
code like this:
NavigationLink(destination:
DiscountsView(selectFunc: { (discount: DessertDiscount) in
self.collection.discount = DiscountEntity(discount: discount)
self.testDesc = discount.name
})
) {
Text("优惠方案:\(self.collection.discount.name)")
.font(ViewApperance.shared.font)
.foregroundColor(ViewApperance.shared.fontColor)
}
)
The data Of collection not update, but testDesc update work, is anyone know what happen in this case, and what is the priciple of Object update in Swift?

Related

SwiftUI picker save return object

I have a background in .NET backend and I have decided to learn swift.
It is going very well, but I have a few issues in SwiftUI.
My problem right now is with the picker.
My goal is to pick an item from the picker, return the object and save the object in a variable, so I can post it to api.
The picker is a list of recipes from API, with: name and ID.
I can populate the picker just fine and get the object back, but I can’t save it.
I got the picker and with the selection I can easy get the name.
But how do I save the full object?
Picker("Pick a recipe", selection: $selectedItem) {
ForEach(recipes, id: \.self) { recipe in
Text(recipe.name)
// var res = recipe - I can’t do that, what do I do then?
}
}

How does the pattern of assigning `#State` in `onReceive` ensure that view state is in sync?

I'm having a little trouble with the following pattern which integrates Combine publishers into SwiftUI so that view state is updated when publishers emit:
struct ItemList: View {
var publisher: AnyPublisher<[Item], Never>
#State private var items = [Item]()
var body: some View {
List(items) { item in
ItemRow(item: item)
}
.onReceive(publisher) {
items = $0
}
}
}
Above example from Swift by Sundell
I feel like I'm missing something when I read it.
Let's assume you initialize items to the correct (at that time) value. What ensures that the published value won't change between the creation of ItemList and the first call to body, where it first starts listening to changes? Or if there is no such guarantee, then what else is preventing the view from ending up in the wrong initial state because of this?
Consider a NavigationLink:
NavigationLink(
destination: { ItemList(publisher: myPub) },
label: { Text("Show List") }
)
Here we have a case where SwiftUI creates the ItemList immediately, but doesn't ask the ItemList for its body until the user taps the link.
(How do we know it creates the ItemList immediately? The destination argument is not declared #escaping, so SwiftUI has to call it inside the NavigationLink initializer.)
So in fact there is a real risk in this case that items should change between when the ItemList is created and when it appears on screen.
We solve this by using a publisher like CurrentValueSubject that publishes its current value immediately to each new subscriber. That way, it doesn't matter how much later SwiftUI decides to use the view. As soon as SwiftUI uses the view, it subscribes to the publisher and immediately gets the current value. SwiftUI can handle that update before updating the framebuffer, so the user doesn't see a flash of incorrect data.
We need to read it in sequence:
State is initiailzed, supposing items = [Item1, Item2, Item3]
body is called to render view
List is constructed with current items, ie. List([Item1, Item2, Item3])
onReceive is called on constructed List of 3) and creates view around that list with subscriber to publisher
subscriber requests current events from publisher
if there are events in publisher then onReceive's closure handler is called (see below) otherwise no changes and List of 3) is shown on screen
6.1. if handler gets same initial [Item1, Item2, Item3] (subscriber extracts all available items) then state is not changed and List of 3) is shown on screen
6.2. if handler gets different items [ItemX, ItemY] then state change invalidates view and List is rebuilt with [ItemX, ItemY] which are shown on screen (there is no cycling because refresh is synchronous and we get into 6.1 at second pass).
That's simplified logic of provided code snapshot.

SwiftUI changing environment object re-created observed object in same view

So, I have few steps, last one contains EnvironmentObject and ObservedObject. The issue is, when I try to modify EnvironmentObject (lane 68) it re-creates ObservedObject.
Can any one explain me why this happens? Any solution to keep my ObservedObject with original state?
As far as I know it possible to change ObservedObject to StateObject, but I am using iOS 13+ so... I need other solution.
Line 47 - body is reevaluated so new instance of ObservedStuff is created, so make it as property and pass it in, like
struct TestView_A: View {
...
private let model = ObservedStuff()
var body: some View {
NavigationLink(destination: TestView_B(viewModel: self.model) ...
}
}

In a typical list -> details SwiftUI app, what is the best way to create new elements?

In a typical list -> details SwiftUI view, I have basically an Array of objects, and for read/edit, I can easily bind these (using #Binding on the view) to view and edit the elements in the array.
What about adding new elements?
I would like to re-use my views for editing; but they expect an #Binding as I mentioned. How do I transition to this view if I want to allow the user to add a new element to the list?
One option is that I can pre-create an object before loading the view, and then binding the view to the new element. However, this makes "cancel" clunky (now I have to remove from the list). Also, it's not clear how to inject this logic (create a new element) in a NavigationLink.
Another option is that I can pass the list to the view and bind a constant empty object, and in the view I can manage adding the new element to the list upon successful creation.
What is the recommended approach to this? I see a lot of tutorials on how to edit and view lists, but not on how to add.
Sounds like you need a backing database. I used Apple's Core Data to add and retrieve stored objects to/from. Here's the guide I used: https://www.hackingwithswift.com/books/ios-swiftui/how-to-combine-core-data-and-swiftui
I figured out a way to do this that is quite nice.
What I've done is that in the list (say, LandmarkList), I added a default LandMark element (which represents the new element to add).
#Published var newLandMark : Landmark
I wrap my view with a new view, which binds against the list:
struct NewLandmarkView : LandmarkDetail {
#Binding var landmarkList : LandmarkList
}
This view adds buttons for save and cancel. Add takes the newLandmark and adds it to the list.
I then use the following to show modally (you can navigate to it if you want instead):
Button(action: {
// In the folder list view, we'll add a note to the "notes" folder
self.showModal = true
}) {
Image(systemName: "square.and.pencil")
}.sheet(isPresented: self.$showModal) {
CreateLandmarkView(landmarkList: self.$landmarkList)
}
This worked pretty well for me as a pattern.

data-dialog created dynamically

I'm using polymer 1.0.
I'm trying to open a with on a clic on an element created dynamically with template repeat.
Here is the code :
<paper-button
data-dialog="modal"
on-click="dialogClick">
Click
</paper-button>
and the script (from doc) :
dialogClick: function(e) {
var button = e.target;
while (!button.hasAttribute('data-dialog') && button !== document.body) {
button = button.parentElement;
}
if (!button.hasAttribute('data-dialog')) {
return;
}
var id = button.getAttribute('data-dialog');
var dialog = document.getElementById(id);
alert(dialog);
if (dialog) {
dialog.open();
}
}
This work only if the value of data-dialog is simple text. If I want to change it by data-dialog="{{item.dialogName}}" for instance, it doesn't work. It is not found by the while loop and exit with the if. in the source code of the page, there is no data-dialog in the paper-button.
Any idea ?
I've ran into a similar problem when using data attributes on custom elements. You might want to subscribe to this polymer issue.
As a workaround, place the data attribute in a standard element that is a parent of the button and search for that one instead.
Also, you might want to consider using var button = Polymer.dom(e).localTarget instead of directly accessing e.target, since the later will give you an element deeper in the dom tree under shady dom.