Created
May 3, 2024 16:43
-
-
Save takoikatakotako/31cfe87d66735dad78d117ae0b069130 to your computer and use it in GitHub Desktop.
SwiftUIでObservableObjectの@publishedなプロパティとBindingする
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import SwiftUI | |
struct AddItemView: View { | |
@StateObject var viewState: AddItemViewState | |
init(items: Binding<[String]>) { | |
self._viewState = StateObject(wrappedValue: AddItemViewState(items: items)) | |
} | |
var body: some View { | |
VStack { | |
Text("Count: \(viewState.items.count)") | |
Button { | |
viewState.addItem() | |
} label: { | |
Text("Add Item") | |
} | |
} | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import SwiftUI | |
class AddItemViewState: ObservableObject { | |
@Binding var bindingItems: [String] | |
@Published var items: [String] { | |
didSet { | |
bindingItems = items | |
} | |
} | |
init(items: Binding<[String]>) { | |
self.items = items.wrappedValue | |
self._bindingItems = items | |
} | |
func addItem() { | |
items.append("Mac Book Pro") | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import SwiftUI | |
struct ContentView: View { | |
@State var items: [String] = [] | |
@State var showingSheet: Bool = false | |
var body: some View { | |
VStack { | |
Text("Count: \(items.count)") | |
Button { | |
showingSheet = true | |
} label: { | |
Text("Show Sheet") | |
} | |
} | |
.sheet(isPresented: $showingSheet) { | |
AddItemView(items: $items) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment