1

So I was reading about the Navigation in the Apple UI guidlines. In SwiftUI, for hierarchical navigation we use the NavigationLink-View. Flat navigation is for example the view for each song in apple music.

My questions:

  1. I have a solution but I wonder what is the best practice solution.

  2. Furthermore, I have to add the animation myself, whereas with NavigationLink I get it for "free". Why does the transition not work? I'm trying to get a similar animation as in apple music when skipping a song.

import SwiftUI

struct Song:Identifiable{
    var id = UUID()
    var name:String
    var cover = Color(red: Double.random(in: 0...1), green: Double.random(in: 0...1), blue: Double.random(in: 0...1))
}

struct ContentView: View {
    var songs:[Song] = []

    init(){
        for i in 0...1000{
            self.songs.append(Song(name: "Song \(i)"))
        }
    }

    @State var index = 0
    var body: some View {
        VStack{
            DetailView(song:songs[index])
                .transition(.asymmetric(insertion: .move(edge: .leading), removal: .move(edge: .trailing)))
            SongNavigation(index:$index, totalSongs: songs.count)

        }.padding()
    }
}

struct DetailView: View{
    var song:Song
    var body: some View{
        VStack{
            Text(song.name)
        }.frame(minWidth:0, maxWidth: .infinity, minHeight: 0, maxHeight: .infinity).background(song.cover)
    }
}

struct SongNavigation:View{
    @Binding var index:Int
    var totalSongs:Int

    var body: some View{
        HStack{
            Button("previous"){
                withAnimation(){
                    if self.index > 0{
                        self.index -= 1
                    }
                }
            }
            Spacer()
            Button("next"){
                withAnimation(){
                    if self.index != self.totalSongs-1 {
                        self.index += 1
                    }
                }
            }
        }
    }
}

preview

simibac
  • 7,672
  • 3
  • 36
  • 48
  • You might find helpful the approach I provided in [this](https://stackoverflow.com/questions/58908741/how-do-i-add-animations-to-transitons-between-custom-navigationitems-made-from-a/59087574?r=SearchResults&s=1|34.4903#59087574) post. – Asperi Dec 10 '19 at 09:40
  • yes @Asperi your solution work – Hardik Bar Dec 10 '19 at 10:53

0 Answers0