gpt4 book ai didi

ios - 如何为绑定(bind)或状态进行值转换

转载 作者:行者123 更新时间:2023-12-01 19:38:36 25 4
gpt4 key购买 nike

我试图了解如何将值(value)从模型转换为 View 。例如,我有一个模型:

struct BloodPressure {  
var systolic: Int = 0
var diastolic: Int = 0
}

我有一个观点:
struct MeasurementsTabView: View {
@State private var bloodPressure = BloodPressure()

var body: some View {
VStack {
TextField("Systolic", text: $bloodPressure.systolic)
TextField("Diastolic", text: $bloodPressure.diastolic)
}
}
}

有错误,因为 text参数应该是一个字符串,但是 bloodPressure.systolicInt .

我找到了一个解决方案,但我认为这并不优雅:
var body: some View {
let systolicBinding = Binding <String> (
get: { String(self.bloodPressure.systolic) },
set: {
if let int = Int($0) {
self.bloodPressure.systolic = int
}
})

let diastolicBinding = Binding <String> (
get: { String(self.bloodPressure.diastolic) },
set: {
if let int = Int($0) {
self.bloodPressure.diastolic = int
}
})

return VStack {
TextField("Systolic", text: systolicBinding)
TextField("Diastolic", text: diastolicBinding)
}
}

你如何解决类似的问题?

最佳答案

在这种情况下,我建议引入 ViewModel 层,因此 BloodPressure 仍然是纯模型。

下面是概念的简化演示(例如,文本字段的格式/验证超出范围等)

import SwiftUI
import Combine

struct BloodPressure {
var systolic: Int = 0
var diastolic: Int = 0
}

class BloodPressureViewModel: ObservableObject {
var model: BloodPressure

init(_ model: BloodPressure) {
self.systolic = String(model.systolic)
self.diastolic = String(model.diastolic)

self.model = model
}
@Published var systolic: String = "" {
didSet {
self.model.systolic = Int(self.systolic) ?? 0
}
}
@Published var diastolic: String = "" {
didSet {
self.model.diastolic = Int(self.diastolic) ?? 0
}
}
}


struct MeasurementsTabView: View {
@ObservedObject var viewModel: BloodPressureViewModel

init(bloodPressure: BloodPressure) {
viewModel = BloodPressureViewModel(bloodPressure)
}
var body: some View {
VStack {
TextField("Systolic", text: $viewModel.systolic)
TextField("Diastolic", text: $viewModel.diastolic)
}
}
}

关于ios - 如何为绑定(bind)或状态进行值转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58851202/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com