LoginSignup
3
2

More than 1 year has passed since last update.

ViewModelのPublishedな値をViewでBinding<型>で扱う方法

Posted at

はじめに

ViewModel.swift
class ViewModel: NSObject, ObservableObject {
    @Published var isShowAlert: Bool = false

    /// 省略 ///
}
ContentView.swift
struct ContentView: View {
    @ObservedObject var viewModel = ViewModel()

    var body: some View {
        Button(action: {
            /// 省略 ///
        }) {
            /// 省略 ///
        }
        .alert(isPresented: Binding<Bool>) {
            Alert(title: Text("確認"),
                  message: Text("これはテストです"),
                  dismissButton: .default(Text("OKOK")))
        }
    }
}

このようにViewModelで処理したPublishedな値をViewでBinding<型>で扱いたい場面がありました。

問題点

ContentView.swift
struct ContentView: View {
    @ObservedObject var viewModel = ViewModel()

    var body: some View {
        Button(action: {
            /// 省略 ///
        }) {
            /// 省略 ///
        }
        .alert(isPresented: viewMode.$isShowAlert) {
            Alert(title: Text("確認"),
                  message: Text("これはテストです"),
                  dismissButton: .default(Text("OKOK")))
        }
    }

しかしこのように書くと以下のようなエラーが発生します。

Cannot convert value of type 'Published<Bool>.Publisher' to expected argument type 'Binding<Bool>'

引数に指定するのはPublished<Bool>.Publisherではなく、Binding<Bool>にしてとのこと。

対処法

ContentView.swift
struct ContentView: View {
    @ObservedObject var viewModel = ViewModel()

    var body: some View {
        Button(action: {
            /// 省略 ///
        }) {
            /// 省略 ///
        }
        .alert(isPresented: $viewModel.isShowAlert) {
            Alert(title: Text("確認"),
                  message: Text("これはテストです"),
                  dismissButton: .default(Text("OK")))
        }
    }

このように書くことでBinding<Bool>として扱えるようです。

参考にした記事

おわりに

今回はViewModelのPublishedな値をViewでBinding<型>で扱う方法について書きました。

ご覧いただきありがとうございました。
こうしたほうがいいや、ここはちょっと違うなど気になる箇所があった場合、ご教示いただけると幸いです。

2022年はiOS開発がどのように変化するのかが楽しみです!

お知らせ

現在、副業でiOSアプリ開発案件を募集しています!
全活動リンクをURLにまとめました。
https://linktr.ee/sasaki.ken

LinkTree_200×200.001.jpeg

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