
この記事では、Swift5.10およびXcode 15.4における、@State変数に値を渡す方法について、サンプルコードを交えながら説明しております。
初心者の方でも分かりやすいように、サンプルコードに適宜説明を入れながら解説していくので、ぜひご覧ください。
初心者の方でも分かりやすいように、サンプルコードに適宜説明を入れながら解説していくので、ぜひご覧ください。
この記事を読んで分かること…
・@State変数に値を渡す方法
実行環境
・実行環境:SwiftUI + Xcode
・Swift:5.10
・XCode:15.4
・サンプルコードの実行確認日:12月31日(火)
@State変数とは?
概要
@frozen @propertyWrapper
struct State<Value>
@State変数とは値を読み書きできるプロパティラッパーです。
サンプルコード
import SwiftUI
struct BlogView: View {
@State private var message: String = ""
var body: some View {
VStack {
Button("Tap Me!") {
message = "Hello"
}
.padding()
.background(Color.blue)
.foregroundColor(.white)
.cornerRadius(8)
Text(message)
.font(.largeTitle)
.foregroundColor(.purple)
}
.padding()
}
}
#Preview {
BlogView()
}
サンプルコードの説明
◾️行 1: SwiftUI
をインポートしています。
◾️行 2: BlogView
という名前の構造体を定義します。View
型を継承します。
◾️行 3: @State
を付けて変数の値の状態変更を監視します。またprivate
修飾子をつけることで、他のファイルからのアクセスを制限します。String
型のmessage
という変数を定義します。
◾️行 5: VStackを宣言します。
◾️行 6-8: Buttonを宣言します。クロージャーの中で message
にHello
を代入します。
◾️行 9: ボタンの背景色を青色にします。
◾️行 10: ボタンの文字色を白色にします。
◾️行 11: 角丸を8にします。
◾️行 13: message
を表示するためのText
を宣言します。fontを.largeTile
に設定し、文字色をpurple
にします。
◾️行 14: 余白を設定します。#PreView
・ここでBlogViewを初期化してあげることで、XCodeの右部分にリアルタイムプレビューを表示させることが可能となります。
出力




まとめ
いかがでしたでしょうか?
この記事では、@Stateを用いて値を渡す方法について解説を行いました。
ではまた、次の記事でお会いしましょう!



この記事があなたのスキルアップに役立ったなら、次のキャリアステップを踏み出す絶好の機会かもしれません。エンジニアとしてのさらなる成長と挑戦を求めるなら、未経験からエンジニア転職なら【Tech Stars Agent】をオススメします!
コメント