投稿の経緯
現在参画中のプロジェクトがチェックボックスを必要とする仕様であり、自作したのでコードを紹介します。
環境
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()
}
}
特に難しい内容ではないと思います。参考にしてください!