How to pass same object to multiple subviews? - swiftui

For each element in my database I want to display a navigation link. The destination and the label of each element should get the same object passed. Now I'm creating for each view a new object. Therefore the UI is not consistent. How can I solve this problem and create exactly one viewModel for each element in the database and pass this to the two subviews?
ForEach(database.decks) { elem in
// looking for a solution like: let viewModel = ViewModel(deck: deck) and pass this
NavigationLink (
destination: DeckDetailView(viewModel: ViewModel(deck: elem)), // <----- this viewModel
label: {
ZStack(alignment: .topTrailing) {
DeckItem(viewModel: ViewModel(deck: elem)) // <----- and this viewModel should be the same!
}
}
)
}

The good reuse design (and simplified view hierarchy, and update when needed explicitly) is to separate that link in standalone view for row, like
ForEach(database.decks) { elem in
DeckRowView(elem: elem)
}
and row
struct DeckRowView: View {
#ObservedObject var vm: ViewModel
init(elem: Deck) {
self.vm = ViewModel(deck: elem)
}
var body: some View {
NavigationLink (
destination: DeckDetailView(viewModel: self.vm),
label: {
ZStack(alignment: .topTrailing) {
DeckItem(viewModel: self.vm)
}
}
)
}
}

Possible solution. Create ViewModel object inside the ForEach and pass.
ForEach(database.decks) { elem in
let vm = ViewModel(deck: elem) //<<-- here
NavigationLink (
destination: DeckDetailView(viewModel: vm), // <----- this viewModel
label: {
ZStack(alignment: .topTrailing) {
DeckItem(viewModel: vm) // <----- and this viewModel should be the same!
}
}
)
}

Related

SwiftUI insert, delete, move and select with smooth animation

I am planning to implement following features in the SwiftUI list - delete, insert, move and select.
With the existing list I am able to delete a row. But can't select a row does not work with List(selection: self.$selectedObject). When I hit edit it always enters into delete mode. And I comment the delete code nothing happens when I tap on edit button. This the first problem.
Also, selectedObject can it be moved to Model instead of keeping it with the ContentView?
Like UITableView, I am not able to get the insert green button. Is it like SwiftUI does not support the green insert button?
Overall trying to understand how the insert, delete, move and select functionality can work with the List SwiftUI.
Another problem I have noticed is that animation is very fast and not smooth when it enters into edit mode (with delete actions).
struct ContentView: View {
#StateObject private var model = Model()
#State var selectedObject: Locations?
var body: some View {
NavigationView {
List(selection: self.$selectedObject) {
ForEach(model.identifiableLocations) { location in
Text(location.name)
}
.onDelete(perform: delete(of:))
}.listStyle(.plain)
.navigationTitle("Places")
.toolbar {
EditButton()
Button {
model.addLocation(name: "Test")
} label: {
Image(systemName: "plus")
}
}
}
}
func delete(of indexSet: IndexSet){
indexSet.forEach { index in
model.delete(itemAt: index)
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView().previewDevice(PreviewDevice(rawValue: "iPhone 14"))
}
}
extension ContentView {
#MainActor class Model: ObservableObject {
#Published private(set) var identifiableLocations = [Locations(name: "USA"),
Locations(name: "Switzerland")]
}
}
extension ContentView.Model {
func addLocation(name: String) {
identifiableLocations.append(Locations(name: name))
}
func delete(itemAt index: Int) {
identifiableLocations.remove(at: index)
}
}
struct Locations {
var name: String
}
extension Locations: Identifiable,Hashable {
var id: String {
return UUID().uuidString
}
}
to make selection work, the list cells need a .tag(). This value is going into the selection var.
yes, selectedObject can be moced to the view model as an additional #Published var
SwiftUI List does not have an insert method, but your Add Button already does that.
The animation is broke because your id in Location is not stable, but generated on each call by the computed var. id should be stable!
Here a running code with comments:
#MainActor
class ViewModel: ObservableObject {
#Published private(set) var identifiableLocations = [
Locations(name: "USA"),
Locations(name: "Switzerland")
]
// published selection var
#Published var selectedObject: Locations?
func addLocation(name: String) {
identifiableLocations.append(Locations(name: name))
}
func delete(itemAt index: Int) {
identifiableLocations.remove(at: index)
}
// new move func
func move(fromOffsets: IndexSet, toOffset: Int) -> Void {
identifiableLocations.move(fromOffsets: fromOffsets, toOffset: toOffset)
}
}
struct Locations: Identifiable, Hashable {
let id = UUID() // id has to stay stable
// var id: String {
// return UUID().uuidString
// }
var name: String
}
struct ContentView: View {
#StateObject private var viewModel = ViewModel()
// #State var selectedObject: Locations? // is now in viewmodel
var body: some View {
NavigationView {
List(selection: $viewModel.selectedObject) {
ForEach(viewModel.identifiableLocations) { location in
Text(location.name)
.tag(location) // this makes selction work
}
.onDelete(perform: delete(of:))
.onMove(perform: viewModel.move)
}
.listStyle(.plain)
.navigationTitle("Places")
.toolbar {
EditButton()
Button {
viewModel.addLocation(name: "Test")
} label: {
Image(systemName: "plus")
}
}
}
}
func delete(of indexSet: IndexSet){
indexSet.forEach { index in
self.viewModel.delete(itemAt: index)
}
}
}

How can use a detail view for editing a observed object and use for add a new value

in the moment I have two views for editing and for add a new item. How can I open the view for editing the item with nil to the observed object and then use for add a new item?
I would open the detailview with this code, but the try to open with the Button "open edit as new" with selectedTool as nil would not work.
var body: some View {
NavigationView {
List {
ForEach(tools) { tool in
NavigationLink {
ToolsEditView(selectedTool: tool)
} label: {
Text("\(tool.wrappedName) | \(Int(tool.ankle))°")
}
}
.onDelete(perform: deleteItem)
}
.navigationTitle("grindingtools")
.navigationBarItems(trailing: addButton)
Button(action: {
ToolsEditView(selectedTool: nil?)
}, label: {
Text("open edit as new")
})
}
}
In the detailview I have in the moment only the saveChanges for the selected item. And in the .onAppear, I get the selected data. But I feel in the moment, that I be on the point, where I need a little tip in which way I have to look
struct ToolsEditView: View {
#Environment(\.presentationMode) var presentationMode
#ObservedObject var selectedTool: ToolsEntity
#State private var toolname: String = ""
#State private var winkel: Double = 0
var body: some View {
Form {
VStack {
TextField("add toolname", text: $toolname)
.textFieldStyle(TextTextFieldStyle(icon: Image(systemName: "pencil")))
}
VStack {
HStack {
Text("grindankle")
.frame(maxWidth: .infinity, alignment: .leading)
.frame(width: 100)
.onAppear { self.toolname = self.selectedTool.wrappedName }
Slider(value: $winkel , in: 0.0...32.0, step: 1.0)
.onAppear { self.winkel = self.selectedTool.ankle }
Text(
String(format: "%.0f °", winkel)
)
}
}
VStack {
HStack {
Button("chancel") {
presentationMode.wrappedValue.dismiss()
}
.buttonStyle(ChancelButton())
Button("save") {
saveChanges()
}
.buttonStyle(AddButton())
}
}
}
.onTapGesture {
hideKeyboard()
}
}
private func saveChanges() {
selectedTool.name = toolname
selectedTool.ankle = winkel
try? selectedTool.managedObjectContext?.save()
presentationMode.wrappedValue.dismiss()
}
}
You will need a custom initializer for your view. The way you have it set up means that the view expects a fully fledged Core Data entity and you are trying to pass nil. In order to do what you are attempting, your view would have to look like this:
struct ToolsEditView: View {
#Environment(\.presentationMode) var presentationMode
// For the sake of the answer, I am assuming you injected the
// ManagedObjectContext into the environment.
#Environment(\.managedObjectContext) var context
#ObservedObject var selectedTool: ToolsEntity
#State private var toolname: String = ""
#State private var winkel: Double = 0
// selectedTool in the init is allowed to be an optional, even though
// self.selectedTool is non-optional. We handle that below.
init(selectedTool: ToolsEntity?) {
// We try to unwrap selectedTool
if let selectedTool {
// We succeeded in unwrapping selectedTool, so we can assign it.
self.selectedTool = selectedTool
} else {
// selectedTool was nil, so we have to create our own
let newTool = ToolsEntity(context: context)
newTool.name = ...
newTool.ankle = ...
self.selectedTool = newTool
}
}
var body: some View {
...
}
}
Once you get comfortable handling this pattern reliably, look into child contexts.

Whats the best way to get SwiftUI Picker() selection to update on app state change?

I'm trying to make a UI with SwiftUI that lists a collection of things that can be of different kinds and can each be updated. I'd like to make the type settable in the UI with a Picker, and I also want the view to update when the item is modified some other way (say, from another part of the UI, or over the network.)
I like a "redux"-style setup, and I don't want to jettison that.
Here's a simple example that shows two items, each with a "randomize" button that changes the item at random and a Picker that lets you choose the new item type. The latter works as expected: the Picker changes the #State var, the store gets updated, etc. The 'randomize' button updates the store and the let property label, but the #State and the Picker don't update.
I would love some advice on good ways to get this to work the way I want.
import SwiftUI
import Combine
#main
struct PuffedWastApp: App {
var store = Store()
var body: some Scene {
WindowGroup {
ContentView().environmentObject(store)
}
}
}
enum ItemState:String, CaseIterable {
case apple
case bannana
case coconut
}
enum Action {
case set(Int,ItemState)
}
class Store: ObservableObject {
#Published var state:[ItemState] = [.apple, .apple]
func reduce(_ action:Action) {
print("do an action")
switch (action) {
case let .set(index,new_state):
print("set \(index) to \(new_state)")
state[index] = new_state
self.objectWillChange.send()
}
}
}
struct ContentView: View {
#EnvironmentObject var store: Store
var body: some View {
VStack {
ForEach(store.state.indices) { index in
ItemContainer(index: index)
//Text("\(index)")
}
}
.padding()
}
}
struct ItemContainer: View {
#EnvironmentObject var store: Store
let index: Int
var body: some View {
ItemView(
index: index,
label: store.state[index], // let property: updates on change in the Store
localLabel: store.state[index], //#State variable; doesn't update on change in the Store
dispatch: store.reduce
)
.padding()
}
}
struct ItemView: View {
let index: Int
let label: ItemState
#State var localLabel: ItemState
let dispatch: (Action)->()
var body: some View {
HStack{
//Text("\(index)")
Text(label.rawValue)
Text(localLabel.rawValue)
Button("Randomize") { dispatch( .set(index, ItemState.allCases.randomElement() ?? .apple ) ) }
Picker("Item type", selection: $localLabel ) {
ForEach( ItemState.allCases , id: \.self ) {
Text($0.rawValue).tag($0)
}
}.onChange(of: localLabel) { dispatch(.set(index, $0)) }
}
.padding()
}
}
Try changing this line:
#State var localLabel: ItemState
to
#Binding var localLabel: ItemState
and pass it in your ItemView init as:
ItemView(
index: index,
label: store.state[index],
localLabel: $store.state[index],
dispatch: store.reduce
)

SwifUI onAppear gets called twice

Q1: Why are onAppears called twice?
Q2: Alternatively, where can I make my network call?
I have placed onAppears at a few different place in my code and they are all called twice. Ultimately, I'm trying to make a network call before displaying the next view so if you know of a way to do that without using onAppear, I'm all ears.
I have also tried to place and remove a ForEach inside my Lists and it doesn't change anything.
Xcode 12 Beta 3 -> Target iOs 14
CoreData enabled but not used yet
struct ChannelListView: View {
#EnvironmentObject var channelStore: ChannelStore
#State private var searchText = ""
#ObservedObject private var networking = Networking()
var body: some View {
NavigationView {
VStack {
SearchBar(text: $searchText)
.padding(.top, 20)
List() {
ForEach(channelStore.allChannels) { channel in
NavigationLink(destination: VideoListView(channel: channel)
.onAppear(perform: {
print("PREVIOUS VIEW ON APPEAR")
})) {
ChannelRowView(channel: channel)
}
}
.listStyle(GroupedListStyle())
}
.navigationTitle("Channels")
}
}
}
}
struct VideoListView: View {
#EnvironmentObject var videoStore: VideoStore
#EnvironmentObject var channelStore: ChannelStore
#ObservedObject private var networking = Networking()
var channel: Channel
var body: some View {
List(videoStore.allVideos) { video in
VideoRowView(video: video)
}
.onAppear(perform: {
print("LIST ON APPEAR")
})
.navigationTitle("Videos")
.navigationBarItems(trailing: Button(action: {
networking.getTopVideos(channelID: channel.channelId) { (videos) in
var videoIdArray = [String]()
videoStore.allVideos = videos
for video in videoStore.allVideos {
videoIdArray.append(video.videoID)
}
for (index, var video) in videoStore.allVideos.enumerated() {
networking.getViewCount(videoID: videoIdArray[index]) { (viewCount) in
video.viewCount = viewCount
videoStore.allVideos[index] = video
networking.setVideoThumbnail(video: video) { (image) in
video.thumbnailImage = image
videoStore.allVideos[index] = video
}
}
}
}
}) {
Text("Button")
})
.onAppear(perform: {
print("BOTTOM ON APPEAR")
})
}
}
I had the same exact issue.
What I did was the following:
struct ContentView: View {
#State var didAppear = false
#State var appearCount = 0
var body: some View {
Text("Appeared Count: \(appearrCount)"
.onAppear(perform: onLoad)
}
func onLoad() {
if !didAppear {
appearCount += 1
//This is where I loaded my coreData information into normal arrays
}
didAppear = true
}
}
This solves it by making sure only what's inside the the if conditional inside of onLoad() will run once.
Update: Someone on the Apple Developer forums has filed a ticket and Apple is aware of the issue. My solution is a temporary hack until Apple addresses the problem.
I've been using something like this
import SwiftUI
struct OnFirstAppearModifier: ViewModifier {
let perform:() -> Void
#State private var firstTime: Bool = true
func body(content: Content) -> some View {
content
.onAppear{
if firstTime{
firstTime = false
self.perform()
}
}
}
}
extension View {
func onFirstAppear( perform: #escaping () -> Void ) -> some View {
return self.modifier(OnFirstAppearModifier(perform: perform))
}
}
and I use it instead of .onAppear()
.onFirstAppear{
self.vm.fetchData()
}
you can create a bool variable to check if first appear
struct VideoListView: View {
#State var firstAppear: Bool = true
var body: some View {
List {
Text("")
}
.onAppear(perform: {
if !self.firstAppear { return }
print("BOTTOM ON APPEAR")
self.firstAppear = false
})
}
}
Let us assume you are now designing a SwiftUI and your PM is also a physicist and philosopher. One day he tells you we should to unify UIView and UIViewController, like Quantum Mechanics and the Theory of Relativity. OK, you are like-minded with your leader, voting for "Simplicity is Tao", and create an atom named "View". Now you say: "View is everything, view is all". That sounds awesome and seems feasible. Well, you commit the code and tell the PM….
onAppear and onDisAppear exists in every view, but what you really need is a Page lifecycle callback. If you use onAppear like viewDidAppear, then you get two problems:
Being influenced by the parent, the child view will rebuild more than one time, causing onAppear to be called many times.
SwiftUI is closed source, but you should know this: view = f(view). So, onAppear will run to return a new View, which is why onAppear is called twice.
I want to tell you onAppear is right! You MUST CHANGE YOUR IDEAS. Don’t run lifecycle code in onAppear and onDisAppear! You should run that code in the "Behavior area". For example, in a button navigating to a new page.
You can create the first appear function for this bug
extension View {
/// Fix the SwiftUI bug for onAppear twice in subviews
/// - Parameters:
/// - perform: perform the action when appear
func onFirstAppear(perform: #escaping () -> Void) -> some View {
let kAppearAction = "appear_action"
let queue = OperationQueue.main
let delayOperation = BlockOperation {
Thread.sleep(forTimeInterval: 0.001)
}
let appearOperation = BlockOperation {
perform()
}
appearOperation.name = kAppearAction
appearOperation.addDependency(delayOperation)
return onAppear {
if !delayOperation.isFinished, !delayOperation.isExecuting {
queue.addOperation(delayOperation)
}
if !appearOperation.isFinished, !appearOperation.isExecuting {
queue.addOperation(appearOperation)
}
}
.onDisappear {
queue.operations
.first { $0.name == kAppearAction }?
.cancel()
}
}
}
For everyone still having this issue and using a NavigationView. Add this line to the root NavigationView() and it should fix the problem.
.navigationViewStyle(StackNavigationViewStyle())
From everything I have tried, this is the only thing that worked.
We don't have to do it on .onAppear(perform)
This can be done on init of View
In case someone else is in my boat, here is how I solved it for now:
struct ChannelListView: View {
#State private var searchText = ""
#State private var isNavLinkActive: Bool = false
#EnvironmentObject var channelStore: ChannelStore
#ObservedObject private var networking = Networking()
var body: some View {
NavigationView {
VStack {
SearchBar(text: $searchText)
.padding(.top, 20)
List(channelStore.allChannels) { channel in
ZStack {
NavigationLink(destination: VideoListView(channel: channel)) {
ChannelRowView(channel: channel)
}
HStack {
Spacer()
Button {
isNavLinkActive = true
// Place action/network call here
} label: {
Image(systemName: "arrow.right")
}
.foregroundColor(.gray)
}
}
.listStyle(GroupedListStyle())
}
.navigationTitle("Channels")
}
}
}
}
I've got this app:
#main
struct StoriesApp: App {
var body: some Scene {
WindowGroup {
TabView {
NavigationView {
StoriesView()
}
}
}
}
}
And here is my StoriesView:
// ISSUE
struct StoriesView: View {
#State var items: [Int] = []
var body: some View {
List {
ForEach(items, id: \.self) { id in
StoryCellView(id: id)
}
}
.onAppear(perform: onAppear)
}
private func onAppear() {
///////////////////////////////////
// Gets called 2 times on app start <--------
///////////////////////////////////
}
}
I've resolved the issue by measuring the diff time between onAppear() calls. According to my observations double calls of onAppear() happen between 0.02 and 0.45 seconds:
// SOLUTION
struct StoriesView: View {
#State var items: [Int] = []
#State private var didAppearTimeInterval: TimeInterval = 0
var body: some View {
List {
ForEach(items, id: \.self) { id in
StoryCellView(id: id)
}
}
.onAppear(perform: onAppear)
}
private func onAppear() {
if Date().timeIntervalSince1970 - didAppearTimeInterval > 0.5 {
///////////////////////////////////////
// Gets called only once in 0.5 seconds <-----------
///////////////////////////////////////
}
didAppearTimeInterval = Date().timeIntervalSince1970
}
}
In my case, I found that a few views up the hierarchy, .onAppear() (and .onDisappear()) was only being called once, as expected. I used that to post notifications that I listen to down in the views that need to take action on those events. It’s a gross hack, and I’ve verified that the bug is fixed in iOS 15b1, but Apple really needs to backport the fix.

(SwiftUI change detection) What is wrong with this piece of code?

When debugging an issue with an app I am working on, I managed to shrink it down to this minimal example:
class RadioModel: ObservableObject {
#Published var selected: Int = 0
}
struct RadioButton: View {
let idx: Int
#EnvironmentObject var radioModel: RadioModel
var body: some View {
Button(action: {
self.radioModel.selected = self.idx
}, label: {
if radioModel.selected == idx {
Text("Button \(idx)").background(Color.yellow)
} else {
Text("Button \(idx)")
}
})
}
}
struct RadioListTest: View {
#ObservedObject var radioModel = RadioModel()
var body: some View {
return VStack {
Text("You selected: \(radioModel.selected)")
RadioButton(idx: 0)
RadioButton(idx: 1)
RadioButton(idx: 2)
}.environmentObject(radioModel)
}
}
struct ContentView: View {
#State var refreshDate = Date()
func refresh() {
print("Refreshing...")
self.refreshDate = Date()
}
var body: some View {
VStack {
Text("\(refreshDate)")
HStack {
Button(action: {
self.refresh()
}, label: {
Text("Refresh")
})
RadioListTest()
}
}
}
}
This code looks pretty reasonable to me, although it exhibit a peculiar bug: when I hit the Refresh button, the radio buttons stop working. The radio buttons are not refreshed, and keep a reference to the old RadioModel instance, so when I click them they update that, and not the new one created after Refresh causes a new RadioListTest to be constructed. I suspect there is something wrong in the way I use EnvironmentObjects but I didn't find any reference suggesting that what I am doing is wrong. I know I could fix this particular problem in various ways that force a refresh in the radio buttons, but I would like to be able to understand which cases require a refresh forcing hack, I can't sprinkle the code with these just because "better safe than sorry", the performance is going to be hell if I have to redraw everything every time I make a modification.
edit: a clarification. The thing that is weird in my opinion and for which I would want an explanation, is this: why on refresh the RadioListTest is re-created (together with a new RadioModel) and its body re-evaluated but RadioButtons are created and the body properties are not evaluated, but the previous body is used. They both have only a view model as state, the same view model actually, but one have it as ObservedObject and the other as EnvironmentObject. I suspect it is a misuse of EnvironmentObject that I am doing, but I can't find any reference to why it is wrong
this works: (yes, i know, you know how to solve it, but i think this would be the "right" way.
problem is this line:
struct RadioListTest: View {
#ObservedObject var radioModel = RadioModel(). <<< problem
because the radioModel will be newly created each time the RadioListTest view is refreshed, so just create the instance one view above and it won't be created on every refresh (or do you want it to be created every time?!)
class RadioModel: ObservableObject {
#Published var selected: Int = 0
init() {
print("init radiomodel")
}
}
struct RadioButton<Content: View>: View {
let idx: Int
#EnvironmentObject var radioModel: RadioModel
var body: some View {
Button(action: {
self.radioModel.selected = self.idx
}, label: {
if radioModel.selected == idx {
Text("Button \(idx)").background(Color.yellow)
} else {
Text("Button \(idx)")
}
})
}
}
struct RadioListTest: View {
#EnvironmentObject var radioModel: RadioModel
var body: some View {
return VStack {
Text("You selected: \(radioModel.selected)")
RadioButton<Text>(idx: 0)
RadioButton<Text>(idx: 1)
RadioButton<Text>(idx: 2)
}.environmentObject(radioModel)
}
}
struct ContentView: View {
#ObservedObject var radioModel = RadioModel()
#State var refreshDate = Date()
func refresh() {
print("Refreshing...")
self.refreshDate = Date()
}
var body: some View {
VStack {
Text("\(refreshDate)")
HStack {
Button(action: {
self.refresh()
}, label: {
Text("Refresh")
})
RadioListTest().environmentObject(radioModel)
}
}
}
}
What is wrong with this piece of code?
Your RadioListTest subview is not updated on refresh() because it does not depend on changed parameter (refreshDate in this case), so SwiftUI rendering engine assume it is equal to previously created and does nothing with it:
HStack {
Button(action: {
self.refresh()
}, label: {
Text("Refresh")
})
RadioListTest() // << here !!
}
so the solution is to make this view dependent somehow on changed parameter, if it is required of course, and here fixed variant
RadioListTest().id(refreshDate)