SwiftUI 的新手。
我想在 UserSettings 视图中更改字符串 calBudget 并在 ContentView 中将其转换为 Int。第一个问题是整数转换不适用于我的代码。第二个问题是,UserSettings 视图中的每次击键都会生成一个新的 UserSettings 视图,从而创建一堆嵌套视图。
struct ContentView: View {
@AppStorage("calBudget") var calBudget = "1700"
@AppStorage("calsBudget") var calsBudget = 0
var body: some View {
NavigationView {
Form {
Text("Budget: \(self.calBudget)")
Text("to integer \(String(self.calsBudget))")
}.toolbar {
ToolbarItem() {
NavigationLink( destination: UserSettings(calBudget: $calBudget, calsBudget: $calsBudget)) { Text("settings") }
}
}
}
}
}
struct UserSettings: View {
@Binding var calBudget: String
@Binding var calsBudget: Int
var body: some View {
Form {
HStack {
TextField("Budget: ", text: self.$calBudget)
Button(action: {
let calsBudget: Int = Int(self.calBudget ) ?? 1000
}) { Text("make into integer")}
}
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView( )
}
}