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を触ってみた

Posted at

 Storyboardでの開発に挫折して以来Swiftを全く触っていないが、最近作りたいスマホアプリができたのでSwiftUIで再挑戦しようと思いたちました。ということで早速Xcodeを最新版(Version 14.2)にしてやってみました。

今回の目標

タップして1〜10の間の数字を0.05s間隔でランダム表示させて、もう一度タップすると一時停止するプログラムを作成

プロジェクトを作成する

welcome画面で"Create a new Xcode project"を選び、iOSSのAppでNext、InterfaceでSwiftUIにしてプロジェクトの置き場を決めたらCreateでプロジェクトが作られます。

外観をつくる

ContentViewファイルを開きます。
VStackでアイテムを縦に並べることができるので、テキストと円を追加していきます。

struct ContentView: View {
    @State var disp_num = Int.random(in: 1...10)
    var body: some View {
        VStack {
            Text("\(disp_num)")
                .font(.system(size: 250, weight: .black))
                .padding(-1)
            Circle()
                .foregroundColor(.red)
                .frame(width: 300, height: 300)
        }
    }
}

プレビュー画面はこうなります。ここまでが早い。
view.png

ボタンを押したときにフラグを立てる

円をボタンのように動作させるのにフラグの用意した。

@State var flag = false

Circle()に下記を追加

.onTapGesture {
    self.flag = !flag
}

フラグが立った時に数字をランダム表示

こちらの記事を参考にTimerを使用します。

private let timer = Timer.publish(every: 0.05, on: .main, in: .default).autoconnect()

お作法などは一切分かりませんが、今回はテキストを変えたいのでわかりやすくText()に下記追加します。

.onReceive(timer) { _ in
    if (flag) {
        disp_num = Int.random(in: 1...10)
    }                
}

以上!終わり!

感想

 GUIの開発はProcessingでちょこっとだけの経験値しかない筆者にとって結構馴染みやすいなと感じました。今度こそ挫折せずに何かしらのそれっぽいものを作りたいです。

 一応完成したソースコードも載せておきます。

import SwiftUI

struct ContentView: View {
    @State var disp_num = Int.random(in: 1...10)
    @State var flag = false
    private let timer = Timer.publish(every: 0.05, on: .main, in: .default).autoconnect()

    var body: some View {
        VStack {
            Text("\(disp_num)")
                .font(.system(size: 250, weight: .black))
                .padding(-1)
                .onReceive(timer) { _ in
                    if (flag) {
                        disp_num = Int.random(in: 1...10)
                    }
                }
            Circle()
                .foregroundColor(.red)
                .frame(width: 300, height: 300)
                .onTapGesture {
                    self.flag = !flag
                }
        }
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}
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?