Skip to content

OnSelected Handler #1

@simongiesen

Description

@simongiesen

Hi,

first of all thanks for the great skeleton for the advanced Segemented Control.

Here is the missing OnSelected Handler, please review it.

import SwiftUI

struct SegmentedControl: View {
    
    var items: [String]
    
    @Binding var selectedIndex: Int
    
    var onSelected: ((Int) -> Void)?
    
    @Namespace var namespace
    
    var body: some View {
        ScrollViewReader { proxy in
            ScrollView(.horizontal, showsIndicators: false) {
                HStack {
                    ForEach(items.indices, id: \.self) { index in
                        Text(items[index])
                            .font(.title3)
                            .fontWeight(.semibold)
                            .padding(.horizontal)
                            .padding(.vertical, 8.0)
                            .matchedGeometryEffect(
                                id: index,
                                in: namespace,
                                isSource: true
                            )
                            .onTapGesture {
                                withAnimation {
                                    selectedIndex = index
                                    proxy.scrollTo(index)
                                    onSelected?(index)
                                }
                            }
                    }
                }
            }
            .clipShape(Capsule())
            .padding(8.0)
            .background {
                Capsule()
                    .fill(Material.regular)
                    .matchedGeometryEffect(
                        id: selectedIndex,
                        in: namespace,
                        isSource: false
                    )
            }
            .background {
                Capsule()
                    .fill(Material.thin)
            }
            .clipShape(Capsule())
        }
    }
    
}

struct SegmentedControl_Previews: PreviewProvider {
    static var previews: some View {
        SegmentedControl(
            items: ["Years", "Months", "Days", "All Photos"],
            selectedIndex: .constant(1),
            onSelected: { index in
                print("Selected segment at index: \(index)")
            }
        )
    }
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions