Search code examples
swiftxcodeswiftuicarousel

SwiftUI - How to get currently displayed item index in a carousel?


I'm trying to recreate the same view as the Carrot Weather Layout modifier, that is a carousel on top of a button that, when pressed, would open the detail view of the item currently displayed.

What would be your approach to achieving that? I've tried using onTapesture and onDragGesture to store the value attached to the item but that doesn't seem to be working.

Thanks for the help!

enter image description here


Solution

  • One way might be to use the selection property of a TabView, and tag each of the views inside the TabView with a .tag(index) where index is an int. You can then use a State variable bound to the selection property to know which view was selected.

    import SwiftUI
    
    struct SwiftUIView: View {
        
        @State var tabSelected = 0
        @State var weatherText = "is..."
        
        var body: some View {
            
            VStack {
                
                Spacer()
                
                Text("Weather: \(weatherText)")
                    .font(.largeTitle)
                    .bold()
                
                Spacer()
                
                TabView (selection: $tabSelected) {
    
                      // Add each of the carousel views, e.g.images
                      // First view in carousel
                    Image(systemName:"sun.max")
                        .resizable()
                        .scaledToFit()
                      .tag(1)
    
                    // Second view in carousel
                    Image(systemName:"cloud.rain")
                        .resizable()
                        .scaledToFit()
                      .tag(2)
                }
                .tabViewStyle(PageTabViewStyle(indexDisplayMode: .automatic))
                .indexViewStyle(PageIndexViewStyle(backgroundDisplayMode: .always))
                
                Spacer()
                
                Button("GET WEATHER..") {
                    if(tabSelected == 1)
                    {
                        weatherText = "It's sunny"
                    }
                    else if(tabSelected == 2)
                    {
                        weatherText = "It's raining"
                    }
                }
                
                Spacer()
            }
           
        }
    }