3
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

【SwiftUI】ToggleStyleを使用してCheckBoxを作成する

Posted at

はじめに

SwiftUIにはチェックボックスがありません。
めっちゃ使う場面ありそうなのに。。。

ToggleStyleを使って自作してみます。

サンプルアプリ

Simulator Screen Recording - iPhone 15 - 2023-11-04 at 21.26.51.gif

実装

import SwiftUI

public struct CheckBoxStyle: ToggleStyle {
    public func makeBody(configuration: Configuration) -> some View {
        HStack {
            Button {
                configuration.isOn.toggle()
            } label: {
                Image(systemName: configuration.isOn ? "checkmark.square" : "square")
            }
            .foregroundStyle(configuration.isOn ? Color.accentColor : Color.primary)

            configuration.label
        }
    }
}

extension ToggleStyle where Self == CheckBoxStyle {
    public static var checkBox: CheckBoxStyle {
        .init()
    }
}

使い方

import SwiftUI

struct ContentView: View {
    @State private var isChecked = false
    var body: some View {
        Toggle(isOn: $isChecked) {
            Text("利用規約に同意しました")
        }
        .toggleStyle(.checkBox)
    }
}

おわり

今回はSFSymbolsを使ってチェックボックスを作ってますが、カスタムのViewを作ってオリジナリティを出すのも良さそうです

3
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?