SwiftUIでのボタンの書き方まとめ
公開日: 2024-02-04 18:55:28
更新日: 2024-02-04 23:25:34
SwiftUIでのボタンの使い方をまとめました。
import SwiftUI
struct ContentView: View {
@State private var isPressed = false
@State private var imageButtonPressed = false
var body: some View {
Button(action: {
self.isPressed.toggle()
print("カスタムボタンがタップされました")
}) {
HStack {
Image(systemName: "star.fill") // システムイメージ
.foregroundColor(.yellow)
Text("お気に入り")
.fontWeight(.bold)
}
.padding()
.scaleEffect(isPressed ? 1.5 : 1.0) // タップ時にサイズを大きくする
.foregroundColor(.white)
.background(isPressed ? Color.blue : Color.green)
.cornerRadius(8)
.overlay(
RoundedRectangle(cornerRadius: 8)
.stroke(isPressed ? Color.blue : Color.green, lineWidth: 2)
)
}
.buttonStyle(PlainButtonStyle())
.animation(.easeInOut, value: isPressed)
.disabled(false)
// 読み込んだ画像を使用するボタン
Button(action: {
self.imageButtonPressed.toggle()
print("画像ボタンがタップされました")
}) {
Image("himawari") // ここで画像ファイル名を指定
.resizable() // 画像のサイズを調整可能にする
.scaledToFit() // アスペクト比を保持しつつフィットさせる
.frame(width: 200, height: 100) // 画像のフレームサイズを指定
.padding() // パディング
}
.background(imageButtonPressed ? Color.gray : Color.clear) // タップ状態に応じて背景色を変更
.cornerRadius(10) // 角を丸くする
.animation(.easeInOut, value: imageButtonPressed)
}
}
実行結果


テキスト: ボタンに表示されるテキスト
Button(action: {}) {
Text("ボタン")
}
イメージ:ボタンに表示されるイメージ(システムイメージやカスタムイメージ)
Button(action: {}) {
Image(systemName: "star.fill")
}
背景色:ボタンの背景色
Button(action: {}) {
Text("ボタン")
.padding()
.background(Color.blue)
}
フォント:テキストのフォントスタイルとサイズ
Button(action: {}) {
Text("ボタン")
.font(.headline)
}
パディング:ボタンの内側のスペース
Button(action: {}) {
Text("ボタン")
.padding()
}
枠線:ボタンの周りの枠線
Button(action: {}) {
Text("ボタン")
.padding()
.overlay(
RoundedRectangle(cornerRadius: 8)
.stroke(Color.blue, lineWidth: 2)
)
}
角の丸み:ボタンの角を丸くする
Button(action: {}) {
Text("ボタン")
.padding()
.background(Color.blue)
.cornerRadius(8)
}
アニメーション:ボタンのアクションや外観の変更にアニメーションを適用
@State private var isPressed = false
Button(action: {
isPressed.toggle()
}) {
Text(isPressed ? "アクティブ" : "ボタン")
.padding()
.animation(.easeInOut, value: isPressed)
}
無効状態:ボタンを無効化(タップ不可)にする
@State private var isDisabled = true
Button(action: {}) {
Text("無効なボタン")
}
.disabled(isDisabled)
ボタンスタイル:ボタンの外観スタイル(例:PlainButtonStyle)
Button(action: {}) {
Text("ボタン")
}
.buttonStyle(PlainButtonStyle())