📱

【SwiftUI】Segmented Control的なものを作る

2023/12/24に公開

Picker

Picker | Apple Developer Documentation

記事を参考に Picker で作成してみます。

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表示

image1.gif

背景色や文字色を変更

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() {
        // 背景色
        UISegmentedControl.appearance().backgroundColor = UIColor(Color.appSecondary.opacity(0.4))
        // 選択項目の背景色
        UISegmentedControl.appearance().selectedSegmentTintColor = UIColor(Color.appBackground)
        // 選択項目の文字色
        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

参考URL

SwiftUIでもSegmented Control的なものを使いたい | DevelopersIO

Build a SwiftUI customizable segmented control - LogRocket Blog

【SwiftUI】Bindingを@Bindingに代入する | 2速で歩くヒト

参考リポジトリ

https://github.com/Inxel/CustomizableSegmentedControl

https://github.com/darioGzlez/FloatingSegmentedControl

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

Discussion