简体   繁体   English

如何将我的环境 object 设置为 SwiftUI 中的用户输入?

[英]How do I set my environment object to user input in SwiftUI?

I am currently using tab views to navigate between 4 views in my project, and the initial view is my profileView, where I want the user to input their information and goals, such as age, height etc. **However I am really struggling to find good examples and instructions on how to get user input and set my environment object to that user input.我目前正在使用选项卡视图在项目中的 4 个视图之间导航,初始视图是我的 profileView,我希望用户在其中输入他们的信息和目标,例如年龄、身高等。**但是我真的很难找到有关如何获取用户输入并将我的环境 object 设置为该用户输入的良好示例和说明。 I was thinking of just using forms, but it seems unnecessary and im not too sure how to change the environment object to what the user has set.我正在考虑只使用 forms,但这似乎没有必要,而且我不太确定如何将环境 object 更改为用户设置的环境。 Does anyone have any good documentation they can refer me to, or show me an example of how to get user input and set my environment object to that data.有没有人可以参考我的任何好的文档,或者向我展示如何获取用户输入并将我的环境 object 设置为该数据的示例。 (I am also not sure if this is necessary, as I will also later be storing it in userdefaults or coredata. (我也不确定这是否有必要,因为我稍后也会将它存储在 userdefaults 或 coredata 中。

This is my model class which is my class data for the user.这是我的 model class 这是我为用户提供的 class 数据。 Ignore the set values at the bottom for now, they will all be set to empty when the project is in later development.暂时忽略底部的设置值,项目后期开发时全部设置为空。

class UserInfoModel: ObservableObject {
    
    
    struct UserInfo: Identifiable {
        var id = UUID()
        var firstName: String
        var lastName: String
        var height: Int
        var weight: Int
        var gender: String
        var age: Int
        
    }
    
    struct DailyCalorieGoals: Identifiable{
        var id = UUID()
        var calorieGoal: Int
        var fatGoal: Int
        var proteinGoal: Int
        var carbGoal: Int

    }
    
    struct CurrentCalorieProgress: Identifiable{
        var id = UUID()
        var calorieProgress: Int
        var fatProgress: Int
        var carbProgress: Int
    }
    
    @Published var personUserInfo = UserInfo.init(firstName: "", lastName:"", height: 0, weight: 0, gender: "", age: 0)
    @Published var personDailyCalorieGoals = DailyCalorieGoals.init(calorieGoal: 2400, fatGoal: 0, proteinGoal: 0, carbGoal: 0)
    @Published var personCurrentCalorieProgress = CurrentCalorieProgress.init(calorieProgress: 0, fatProgress: 0, carbProgress: 0)
    
   
}

So when I am in my profile view how do i get the user input and set my environment object to that data?那么当我在我的个人资料视图中时,我如何获取用户输入并将我的环境 object 设置为该数据?

The above has been solved, thanks to the help provides so far, however using the method linked below I get the following, but I am not sure how to change the value of my double environment object to the fatInputString:由于到目前为止提供的帮助,上述问题已经解决,但是使用下面链接的方法我得到以下内容,但我不确定如何将我的双环境 object 的值更改为 fatInputString:

New code to get input from user获取用户输入的新代码

Text("Fat: \(self.person.personDailyCalorieGoals.fatGoal, specifier: "%.0f")g")
                            }
                            TextField("Enter new fat goal (g)", text: $fatInputString ).keyboardType(.numberPad)
                                .onReceive(Just(fatInputString)) { newValue in
                                                let filtered = newValue.filter { "0123456789".contains($0) }
                                                if filtered != newValue {
                                                    self.fatInputString = filtered
                                                }

But how do i set my environment object但是我如何设置我的环境 object

self.person.personDailyCalorieGoals.fatGoal 

equal to等于

self.inputString 

from the above code }从上面的代码}

Using a Form isn't required -- it just makes the formatting of your user input elements a little more standardized on iOS/macOS.不需要使用Form ——它只是让用户输入元素的格式在 iOS/macOS 上更加标准化。

Regardless of whether you use Form or not, you'll be using various user input elements and assigning them Bindings on your UserInfoModel .无论您是否使用Form ,您都将使用各种用户输入元素并在您的UserInfoModel上为它们分配绑定。 SwiftUI/Combine makes this really easy to do with the $ operator. SwiftUI/Combine 使用$运算符使这非常容易。

Here's an example of how to get input to a couple of your fields.这是一个如何获取几个字段输入的示例。 You can see that when the field info changes, the value is reflected in the EnvironmentObject which ContentView owns -- it displays the value at the top above the EditorView可以看到,当字段信息发生变化时,值会反映在ContentView拥有的EnvironmentObject中——它显示在EditorView上方的顶部

struct ContentView : View {
    @ObservedObject var userInfo = UserInfoModel()
    
    var body: some View {
        VStack {
            Text("Name: \(userInfo.personUserInfo.firstName)")
            Text("Weight: \(userInfo.personUserInfo.weight)")
            Text("Carb: \(userInfo.personCurrentCalorieProgress.carbProgress)")
            EditorView().environmentObject(userInfo)
        }
    }
}

struct EditorView : View {
    @EnvironmentObject private var userInfo : UserInfoModel
    
    var body: some View {
        Form {
            TextField("First name", text: $userInfo.personUserInfo.firstName)
            Stepper("Weight", value: $userInfo.personUserInfo.weight, in: 0...500)
            Stepper("Carb progress", value: $userInfo.personCurrentCalorieProgress.carbProgress, in: 0...1000, step: 10)
        }
    }
}

Update based on comments : Edit to show your request about numerical text input:根据评论更新:编辑以显示您对数字文本输入的请求:

struct EditorView : View {
    @EnvironmentObject private var userInfo : UserInfoModel
    @State var fatInputString = "" //<-- Here
    
    var body: some View {
        Form {
            TextField("First name", text: $userInfo.personUserInfo.firstName)
            Stepper("Weight", value: $userInfo.personUserInfo.weight, in: 0...500)
            Stepper("Carb progress", value: $userInfo.personCurrentCalorieProgress.carbProgress, in: 0...1000, step: 10)
            Text("Fat: \(userInfo.personDailyCalorieGoals.fatGoal)g") //<-- Here
            TextField("Enter new fat goal (g)", text: $fatInputString ).keyboardType(.numberPad)
                .onReceive(Just(fatInputString)) { newValue in
                    let filtered = newValue.filter { "0123456789".contains($0) }
                    if filtered != newValue {
                        self.fatInputString = filtered
                    }
                    if let goal = Int(fatInputString), goal != userInfo.personDailyCalorieGoals.fatGoal {  //<-- Here
                        userInfo.personDailyCalorieGoals.fatGoal = goal
                    }
                }
        }
        
    }
}

Note that in your updated code you had a bug where the fat amount would always be displayed as 0. Make sure to look at each line with //<-- Here marked请注意,在您更新的代码中,您有一个错误,即脂肪量始终显示为 0。确保查看每一行带有//<-- Here标记

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在 SwiftUI 中获取我的环境 object 数组的索引? - How do I get the index of my environment object array in SwiftUI? 如何在 SwiftUI (SWIFT) 中创建对象数组作为环境 object - How do I create an array of objects as an environment object in SwiftUI (SWIFT) 当环境对象更新导致同一视图重新加载时,如何导航到另一个 SwiftUI 视图 - How do I navigate to another SwiftUI View when an Environment Object update is causing the same view to reload 如何从我的 SwiftUI Mac 应用程序的“帮助”菜单中显示用户指南? - How do I display User Guides from my Help menu in my SwiftUI Mac app? 如何在 SwiftUI 环境中实现子上下文 (CoreData)? - How do I implement a child context (CoreData) in SwiftUI environment? 用户在 Firebase 上使用 Google 登录后,如何在 swiftUI 中重新呈现我的视图? - How do I rerender my view in swiftUI after a user logged in with Google on Firebase? 如何在我的 SwiftUI 应用程序中初始化我的 ViewModel - How do I initialise my ViewModel in my SwiftUI app 如何将用户分析添加到我的 SwiftUI 应用程序? - How can I add user analytics to my SwiftUI app? 如何在aps-environment设置为“ production”的情况下运行iOS应用(Xcode 6)? - How do I run my iOS app (Xcode 6) with the aps-environment set to “production”? 如何让 SwiftUI 动态响应用户事件? - How do I get SwiftUI to dynamically respond to user events?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM