iTranslated by AI

The content below is an AI-generated translation. This is an experimental feature, and may contain errors. View original article
📱

[SwiftUI] Creating a Segmented Control-like UI

に公開

Picker

Picker | Apple Developer Documentation

I will try creating it with Picker, referring to the documentation.

import SwiftUI

struct PeriodSwitchView: View {
    private enum Periods: String, CaseIterable, Identifiable {
        case day = "日"
        case week = "週"
        case month = "月"
        case year = "年"

        var id: String { rawValue }
    }

    @State private var selectedPeriod = Periods.day

    var body: some View {
        Picker("periods", selection: $selectedPeriod) {
            ForEach(Periods.allCases) {
                Text($0.rawValue).tag($0)
            }
        }
        .pickerStyle(.segmented)
        .padding()
    }
}

struct PeriodSwitchView_Previews: PreviewProvider {
    static var previews: some View {
        PeriodSwitchView()
    }
}

↓ Preview display

image1.gif

Changing background and text colors

import SwiftUI

struct PeriodSwitchView: View {
    private enum Periods: String, CaseIterable, Identifiable {
        case day = "日"
        case week = "週"
        case month = "月"
        case year = "年"

        var id: String { rawValue }
    }

    @State private var selectedPeriod = Periods.day

    init() {
        // Background color
        UISegmentedControl.appearance().backgroundColor = UIColor(Color.appSecondary.opacity(0.4))
        // Background color for the selected segment
        UISegmentedControl.appearance().selectedSegmentTintColor = UIColor(Color.appBackground)
        // Text color for the selected segment
        UISegmentedControl.appearance().setTitleTextAttributes([.foregroundColor: UIColor.white], for: .selected)
    }

    var body: some View {
        Picker("periods", selection: $selectedPeriod) {
            ForEach(Periods.allCases) {
                Text($0.rawValue).tag($0)
            }
        }
        .pickerStyle(.segmented)
        .padding()
    }
}

struct PeriodSwitchView_Previews: PreviewProvider {
    static var previews: some View {
        PeriodSwitchView()
    }
}

image2.png

Reference URLs

I want to use something like a Segmented Control even in SwiftUI | DevelopersIO

Build a SwiftUI customizable segmented control - LogRocket Blog

[SwiftUI] Assigning Binding to @Binding | 2-Soku de Aruku Hito

Reference Repositories

https://github.com/Inxel/CustomizableSegmentedControl

https://github.com/darioGzlez/FloatingSegmentedControl

https://github.com/pratikg29/Custom-SegmentView

Discussion