0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【SwiftUI】簡単なおみくじアプリを作る

Last updated at Posted at 2023-03-20

1,はじめに

SwiftUIの学習のために購入した、
SwiftUI対応 たった2日でマスターできる iPhoneアプリ開発集中講座
を学習している過程で、アウトプットとして簡単なおみくじアプリを作成。

2,簡単に構成をイメージ

  • 画面構成図(上:結果を出力、真ん中:おみくじのイラスト、下:おみくじを引くボタン)
  • おみくじを引くボタンを押すとおみくじの結果が出力される。
  • おみくじとアプリアイコンのイラスト(同じイラストをフリーサイトから持ってきた)

3,コードを書く

おみくじの結果を格納する状態変数

@State var answerNumber = 0

変数に@Stateを付けることで、
値が更新されたらViewがリロード(再描画)され、tructの中で値を変更することができる。

if文でおみくじの結果を判別

// おみくじの数字が0だったら
if answerNumber == 0 {
    // 初期画面のテキストを表示
    Text("今日の運勢は?")
        .font(.title)
    Spacer()
} else if answerNumber == 1 {
    // おみくじの数字が1だったら「大吉」
    Text("大吉")
        .font(.title)
    Spacer()
} else if answerNumber == 2 {
    // おみくじの数字が2だったら「吉」
    Text("吉")
        .font(.title)
    Spacer()
} else if answerNumber == 3 {
    // おみくじの数字が3だったら「中吉」
    Text("中吉")
        .font(.title)
    Spacer()
} else if answerNumber == 4 {
    // おみくじの数字が4だったら「小吉」
    Text("小吉")
        .font(.title)
    Spacer()
} else if answerNumber == 5 {
    // おみくじの数字が5だったら「末吉」
    Text("末吉")
        .font(.title)
    Spacer()
} else if answerNumber == 6 {
    // おみくじの数字が6だったら「凶」
    Text("凶")
        .font(.title)
    Spacer()
} else {
    // おみくじの数字が1~6以外だったら「大凶」
    Text("大凶")
        .font(.title)
    Spacer()
}

おみくじのイラストを配置

イラストはフリー素材。

// おみくじの画像
    Image("おみくじイラスト")
        .resizable()
        .scaledToFit()
        .padding()

おみくじボタンを配置

Int.random(in: 1...6)で、1〜6までのランダムな値を出力する

// おみくじボタン
Button {
    // ボタンがタップされたときの動き(ランダム)
    answerNumber = Int.random(in: 1...6)
    print("タップした!")
} label: {
    // ボタンに表示する文字
    Text("おみくじを引く!")
        .frame(maxWidth: .infinity)
        .frame(height: 70)
        .font(.title)
        .background(Color.pink)
        .foregroundColor(Color.white)
}

4,終わり

参考書籍:「SwiftUI対応 たった2日でマスターできる iPhoneアプリ開発集中講座
コード:https://github.com/Yuchi-SaitoYuya/Omikuji.git

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?