Last active
December 24, 2023 07:18
-
-
Save benigumocom/3ca18c0a1c933800f30a25bbf64b8a49 to your computer and use it in GitHub Desktop.
【SwiftUI】@State を 子 View でどう受けるか 🤔 - @binding 👉 https://android.benigumo.com/20231224/state-binding/
This file contains hidden or 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 | |
import PlaygroundSupport | |
struct ParentView: View { | |
@State private var text: String = "" | |
var body: some View { | |
VStack { | |
TextField("Parent", text: $text) | |
Text(text) | |
Divider() | |
ChildView(text: $text) | |
} | |
.padding() | |
} | |
} | |
//struct ChildView: View { | |
// private var text: Binding<String> | |
// | |
// init(text: Binding<String>) { | |
// self.text = text | |
// } | |
// | |
// var body: some View { | |
// TextField("Child", text: text) | |
// Text(text.wrappedValue) | |
// } | |
//} | |
//struct ChildView: View { | |
// var text: Binding<String> | |
// | |
// var body: some View { | |
// TextField("Child", text: text) | |
// Text(text.wrappedValue) | |
// } | |
//} | |
// NG | |
//struct ChildView: View { | |
// @Binding private var text: String | |
// | |
// init(text: Binding<String>) { | |
// self.text.projectedValue = text // NG | |
// } | |
// | |
// var body: some View { | |
// TextField("Child", text: $text) | |
// Text(text) | |
// } | |
//} | |
// NG | |
//struct ChildView: View { | |
// @State private var text: String | |
// | |
// init(text: Binding<String>) { | |
// self.text = text.wrappedValue | |
// } | |
// | |
// var body: some View { | |
// TextField("Child", text: $text) | |
// Text(text) | |
// } | |
//} | |
// 主流? | |
//struct ChildView: View { | |
// @Binding private var text: String | |
// | |
// init(text: Binding<String>) { | |
// _text = text | |
// } | |
// | |
// var body: some View { | |
// TextField("Child", text: $text) | |
// Text(text) | |
// } | |
//} | |
struct ChildView: View { | |
@Binding var text: String | |
var body: some View { | |
TextField("Child", text: $text) | |
Text(text) | |
} | |
} | |
PlaygroundPage.current.setLiveView( | |
ParentView() | |
.frame(width: 300, height: 300) | |
) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment