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?

More than 1 year has passed since last update.

SwiftUIを触ってみた Part3

Posted at

三日坊主の自分が3回目まで辿り着いて嬉しいというかなんというか。ということでPart1Part2をくっつける(画面遷移させる)のをやってみた。はまりポイントというかよく調べず考えずに作ったらよろしくなかったので今回も備忘録をきちんと残す。

目標

今回の目標も簡単で、TOP画面からPart1で作った抽選機ページにジャンプして、都道府県ランダムマシーンを完成させる。調べた感じNavigationStackが新しくて分かりやすい画面遷移の方法らしかったので、それを使ってみた。

ハマりポイント

ボタンを押す→都道府県CSVを読み込む→抽選機ページに遷移する、という順番で動いて欲しくてこんなことをやってしまった。

        NavigationStack {
            NavigationLink(destination: LotteryView()) { // 遷移先: LotteryView
                // 画面遷移のトリガーとなるViewの定義
                RoundedRectangle(cornerRadius: 35)
                    .overlay(
                        Text("NEXT")
                            .foregroundColor(.white)
                            .frame(height: 100)
                    )
                    .foregroundColor(Color(red: 0.226, green: 0.646, blue: 0.953))
                    .frame(width: 100, height: 50)
                    .onTapGesture {
                        prefArray = loadCSV(fileName: "SampleCSV")
                    }
        }

onTapGestureを画面遷移のトリガーに使ってしまってしまったためにファイル読み込みが終わる前にボタンを離すと画面が遷移してくれない挙動が発生した。長押しすれば画面遷移するけど、ぽちぽちしただけでは画面は遷移しない、といった具合です。
test_gamen.gif

簡単な解決策は遷移先でCSVを読み込むのがよさそうなので、loadCSVを行う場所を変えました。
使うのはこのページなのだからよく考えたらそれはそうですね。初期化をこんな感じに。

    @State var prefArray: [[String]] = []
    @State var index = 0
    @State var flag = false
    
    var prefArrayMaxIndex = 0
    
    init() {
        _prefArray = State(initialValue: loadCSV(fileName: "SampleCSV"))
        prefArrayMaxIndex = prefArray.count-1
        _index = State(initialValue:Int.random(in: 1...prefArrayMaxIndex))
    }

今度は画面遷移うまくいきました。
test2.gif

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?