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:
I have a solution but I wonder what is the best practice solution.
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
}
}
}
}
}
}