リセットボタンを追加したカウンターアプリのコードを紹介します!
このリセットボタンを押すと、カウントが 0 にリセット されます。
リセットボタン追加版のコード
import SwiftUI
struct ContentView: View {
@State private var count = 0 // 状態変数
var body: some View {
VStack(spacing: 20) {
Text("カウンター: \(count)")
.font(.largeTitle)
.padding()
HStack {
Button(action: { count -= 1 }) {
Text("−")
.font(.largeTitle)
.frame(width: 80, height: 80)
.background(Color.red.opacity(0.7))
.foregroundColor(.white)
.clipShape(Circle())
}
Button(action: { count += 1 }) {
Text("+")
.font(.largeTitle)
.frame(width: 80, height: 80)
.background(Color.blue.opacity(0.7))
.foregroundColor(.white)
.clipShape(Circle())
}
}
// リセットボタンを追加
Button(action: { count = 0 }) {
Text("リセット")
.font(.title)
.padding()
.frame(width: 150)
.background(Color.gray.opacity(0.7))
.foregroundColor(.white)
.cornerRadius(10)
}
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
追加したポイント
✅ リセットボタンを Button
で追加
✅ action: { count = 0 }
にして、押したらカウントを0にする
✅ ボタンのデザインを cornerRadius(10)
で四角の角を丸くした
このコードを試して、実際にリセットボタンを押してみてください!
さらに応用するなら…
🔹 リセット時にアニメーションをつける
🔹 カウントが10以上ならリセットボタンの色を変える
こんな風に発展させていくと、SwiftUIの理解が深まりますよ💡😊