LoginSignup
0
3

More than 1 year has passed since last update.

[SwiftUI]チェックボックスを自作する

Last updated at Posted at 2021-10-10

投稿の経緯

現在参画中のプロジェクトがチェックボックスを必要とする仕様であり、自作したのでコードを紹介します。

環境

Swift 5.5
Xcode 13.0

コードの紹介

struct CheckBox: View {
    @State private var isChecked = false // チェックした/していないで変化させる
    var tapAction: () -> Void // CheckBoxを呼んだ時のアクション

    var body: some View {
        Button(action: {
            toggle()
            tapAction()
        }) {
            if isChecked {
                Image(systemName: "checkmark.square.fill")
                    .foregroundColor(.red)
            } else {
                Image(systemName: "square")
                    .foregroundColor(.black)
            }
        }
        .buttonStyle(BorderlessButtonStyle()) // Formで利用する場合に必要
    }

    func toggle() {
        isChecked.toggle()
        UIImpactFeedbackGenerator(style: .medium) // タップでiPhoneがブルっとなる(UX向上)
            .impactOccurred()
    }
}

特に難しい内容ではないと思います。参考にしてください!

0
3
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
0
3