0
0

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】Viewの@BindingプロパティをViewModelに渡す

Posted at

はじめに

Viewに渡された@BindingプロパティをViewModelで使用する場合、ViewModelのイニシャライザでBindingを受け取る必要がある

コード

View.swift
import SwiftUI

struct Item_Image_Select_V: View {
    @StateObject private var viewModel: ViewModel
    @Binding var data: String
    init(data: Binding<String>) {
        self._data = data
        self._viewModel = StateObject(wrappedValue: ViewModel(data: data))
    }
    // hogehoge...
}

ViewModel.swift
import SwiftUI

extension Item_Image_Select_V {
    @MainActor class ViewModel: ObservableObject {
        @Published var dataVM = ""
        private var dataBinding: Binding<String>?
        init(data: Binding<String>) {
            self._dataVM = Published(initialValue: data.wrappedValue)
            self.dataBinding = data
        }
        
        func something() {
            // dataVMを処理し、自身のViewに反映。また、同様にdataBindingも更新し、親Viewに反映
            // つまり、2つのプロパティを更新する必要がある
        }
    }
}
0
0
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
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?