我试图在一个视图之间传递一些变量,您将它们(configView)设置为personalView,在那里它们可以被读取和更改。
我做了一个新的应用程序来简化和重写一些混乱的代码,所以它现在相当简单。
personalView
import SwiftUI
import Combine
struct personalView: View {
@Binding var initNum: Int
var body: some View {
Text("Personal")
Text(initNum)
}
}
struct personalView_Previews: PreviewProvider {
static var previews: some View {
personalView()
}
}
configView
// configView.swift
import SwiftUI
import Combine
struct configView: View {
private enum Field: Int, CaseIterable {
case initNum, playerNum
}
@State var playerNum: Int = 1
@State var initNum: Int = 1
@FocusState private var focusedField: Field?
var body: some View {
VStack {
NavigationView {
VStack {
HStack {
TextField("S", value: $initNum, formatter: NumberFormatter()
)
.padding([.top, .leading, .bottom])
.keyboardType(.numberPad)
.font(.system(size:40))
.frame(width: 60)
.focused($focusedField, equals: .initNum)
Text("Starting Card")
.font(.system(size:40))
}
HStack {
TextField("P", value: $playerNum, formatter: NumberFormatter()
)
.padding([.top, .leading, .bottom])
.keyboardType(.numberPad)
.font(.system(size:40))
.frame(width: 60)
.focused($focusedField, equals: .playerNum)
.toolbar {
ToolbarItem(placement: .keyboard) {
Button("Done") {
focusedField = nil
}
}
}
Text("Players")
.font(.system(size:40))
}
}
}
}
}
}
struct configView_Previews: PreviewProvider {
static var previews: some View {
configView()
}
}
我试着看其他Stack Overflow帖子,但不断得到错误,因为它是一个Int而不是一个字符串。
有人建议@EnvironmentObject可以是一个很好的选择,特别是如果你计划在深度嵌套的视图中访问数据/配置
还要确保你的视图名称使用了正确的约定。Swift中没有驼峰式的结构/类。
class UserConfig: ObservableObject {
@Published var userId: Int?
}
struct ConfigView: View {
@EnvironmentObject private var userConfig: UserConfig
var body: some View {
VStack {
Button("Assign Id") {
userConfig.userId = 12 // assign some id
}
}
}
}
struct PersonalView: View {
@EnvironmentObject private var userConfig: UserConfig
var body: some View {
if let userId = userConfig.userId {
Text("(userId)")
}
}
}
struct ContentView: View {
var body: some View {
VStack {
Text("Hello World")
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
.environmentObject(UserConfig())
}
}