1
3

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 3 years have passed since last update.

@ObservedObjectと@Publishedを使ってみた

Posted at

#はじめに
前回、@State@Bindingについて記事を書いたので、今回は@ObservedObject@Publishedについて見ていきます。
@ObservedObject@Publishedを使用することでオブジェクトのプロパティの変化を観測することができます。

#@Published
ObservableObjectプロトコルに準するAnimalクラスを作成し、プロパティのkind,name,voiceの値を観測させます。
観測対象のプロパティには@Publishedをつけます。

Animal.swift

import SwiftUI

class Animal:ObservableObject{
    @Published var kind = ""
    @Published var name = ""
    @Published var voice = ""
}

#@ObservedObject

観測する対象のオブジェクトに@ObservedObjectをつけて変数を設定します。

ContentView.swift
import SwiftUI

struct ContentView: View {
    @ObservedObject var animal = Animal()
    
    var body: some View {
        VStack (alignment:.leading, spacing:15){
            Group{
                TextField("種類",text:$animal.kind)
                TextField("名前",text:$animal.name)
                TextField("鳴き声",text:$animal.voice)
            }.textFieldStyle(RoundedBorderTextFieldStyle())
            Text("\(show(kind: animal.kind, name: animal.name, voice: animal.voice))")
        }.frame(width:200)
    }
    
    func show(kind:String,name:String,voice:String)-> String {
        if !kind.isEmpty || !name.isEmpty || !voice.isEmpty {
            return "\(kind)\(name)\(voice)と鳴きます!"
        }else{
            return ""
        }
        
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

3つのテキストフィールドに入力を行うと、即時画面下部にメッセージが反映されます。

#参考
SwiftUI iPhoneアプリ開発入門ノート

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?