TEAM LICENSES: Save money and learn new skills through a Hacking with Swift+ team license >>

SOLVED: How best to navigate to view of just added object

Forums > SwiftUI

After successfully adding a core data object, I am showing an alert which says the object(match) was created and has a dismiss button which which can just dismiss the message, but it leaves the view open to creat another object instead of navigating to the match just created, which is the most likely desired use case.

I get two warnings in this code which say MatchView initializer is unused, but the code compiles and runs correctly except it still does not navigate to MatchView, still stays in the NewMatch View.

Any suggestions?

```   Button("Add") {
            // Add match to core data
            tables = Int(maxPlayers)!/4
            errormsg = MatchModel.validateGame(tt: Int(tables) , bpr: Int(boardsPerRound) ?? Int(2), pairs: pairs)
            if errormsg != "none" {
                showingAlert = true
                print("Error ==>", errormsg, pairs.description, maxPlayers.description, tables.description)
            }
            else {
                showingAlert = false
                showingConfirm = true
                addMatch()
            }
            clearMatch()
            // Navigate to the list
            tabSelection = Constants.showMatch
            self.presentationMode.wrappedValue.dismiss()
            }.padding()
                    .alert(errormsg, isPresented: $showingAlert){
                        Button("Dismiss", role: .cancel) {}
                    }
                    .alert(confirmmsg, isPresented: $showingConfirm){
                        Button("Dismiss"/*, role: .cancel */) {
                            let match = Match(context: viewContext)
                            let score = Score(context: viewContext)
                            print(" show match View?")
                            MatchView(match: match ,score: score)
                      }
                    }

2      

hi Sandy,

if you add a new match and score object and want to navigate to a MatchView after tapping the "dismiss" button (?), then place a hidden NavigationLink in the enclosing view, something like this:

NavigationLink(destination: MatchView(match: selectedMatch!, score: selectedScore!),
                                                 isActive: $navLinkForMatchIsActive) { EmptyView() }
                        .hidden()

where selectedMatch is a @State variable of type Match?, selectedScore is a @State variable of type Score?, and navLinkForMatchIsActive is a @State variable of type Bool initially set to false (and also set the first two to nil and the third to false when the view appears in .onAppear).

when the button is tapped and you want this to trigger a navigation to an appropriate match and score, just add these in the action for the button

selectedMatch = Match(context: viewContext)
selectedScore = Score(context: viewContext)
navLinkForMatchIsActive = true

as for the message "MatchView initializer is unused," just writing MatchView(match: match ,score: score) in the button's action doesn't trigger any navigation nor does it have any visual effect (and that's what the error is telling you, effectively -- it's being invoked in some context which is not visual).

hope that helps,

DMG

2      

Hi Jerry, - THANKS.

I figured the error was telling me, "this is not going to work", changed the button code as follows but now on the line with hidden it says Warning - "Result of call to 'hidden()' is unused

Also, didn't add an .onAppear, I thought it should go at beginning of view, but can't find example of format yet.

Also, I will put this verion on GitHub, it is public, my userid is SKRC and the name of the project is DuplicateScore-V-2.2,https://github.com/skrc/-DuplicateScore-V-2.2, I am happy if you want to download and run, if so skip the Club and Player Options, only minimal code down at this point. Did you tell me you have a Chicago Bridge Score App?

 Button("Dismiss"/*, role: .cancel */) {
                                //  Code following does not work
                                let match = Match(context: viewContext)
                                let score = Score(context: viewContext)
                                navLinkForMatchIsActive = true
                                print(" show match View?")
                                NavigationLink(destination: MatchView(match: match, score: score), isActive: $navLinkForMatchIsActive) { EmptyView() }
                                    .hidden()     //Result of call to 'hidden()' is unused
                                // end of code that doesn't work.
                            }

2      

hi Sandy,

my suggestion was that the NavigationLink be attached to the enclosing view where the button was located, not just that it replace the direct call to MatchView in the button's executable code.

i will take a look at your code; i'll get back to you. i have also tried out your app on the App Store, so i have some sense on what you're trying to build.

and yes, i do have some code for Chicago bridge scoring that uses Core Data so that all meetings of our club are saved and shared across (personal) devices, and that can be recalled and examined using simple statistics (think Swift Charts when iOS 16 comes out). i suspect that's where you're next trying to take your app.

hope that helps,

DMG

2      

Ahhhh, that makes sense. Was stuck in my- do after the dismiss paradigm - instead of at the beginning of the view. Should work.

When you look at my existing code - it will be ugly, I leave lots of commented code until I'm closer to moving to production. The new version look visually lots better than the original, and the UI is considerably more friendly. I am currently on the fence on whether to make it just run on ipad since it has the additional bid function that really can use the real estate. Very awkward for iphone at the moment and I haven't taking time to focus on it.

Yes, I would hope to add some statistics using the swift charts coming later.
Did you do your app with Cloud Kit - was thinking that is my logical next step?

I will pretty shortly put this version up on TestFlight. I am using it already for both of my duplicate clubs and am pretty confident in the reliability for that purpose.

Curious about your Chicago Bridge app - Is it on GitHub? friends of our were trying that and wondering how you do the rotations etc for your club, we have no experience with that. We were doing with just a foresome and doing plain 4 hand round robin.

2      

hi Sandy,

it looks like you're closer to a solution of your original problem.

be sure to check the Apple documentation on NavigationLink, where you'll find simple examples for cases where

  • Users click or tap a navigation link to present a view ...
  • Alternatively, you can use a navigation link to perform navigation based on a presented data value ...

your situation falls into the second of these two.

hope that helps,

DMG

i'll get back to you off-line on your questions about bridge.

2      

Hacking with Swift is sponsored by String Catalog.

SPONSORED Get accurate app localizations in minutes using AI. Choose your languages & receive translations for 40+ markets!

Localize My App

Sponsor Hacking with Swift and reach the world's largest Swift community!

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.