You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将对象不同类型变量单独传至子视图并复用ClearButtonView

问题解答

1. 这属于泛型的应用场景吗?

是的,这是泛型的典型应用场景。我们需要让ClearButtonView兼容不同类型的可绑定属性(比如Double类型的cost、Int类型的mileage),泛型可以让视图脱离具体类型的限制,实现跨场景复用。

2. 实现方法

我们可以通过泛型+Binding的组合来实现,借助Swift的Numeric协议做类型约束(Double和Int都遵循该协议,且都支持赋值0),让视图能接收任意符合要求的绑定值,点击时将其重置为0。

修改后的ClearButtonView

struct ClearButtonView<Value: Numeric>: View {
    @Binding var value: Value
    
    var body: some View {
        Image(systemName: "xmark.circle.fill")
            .foregroundColor(.secondary)
            .padding(.trailing, 10)
            .onTapGesture {
                value = 0
            }
    }
}

父视图中的使用示例

假设父视图持有@Bindable的Servicing实例,可分别为cost和mileage传入对应绑定:

struct ParentView: View {
    @Bindable var service: Servicing
    
    var body: some View {
        VStack(spacing: 16) {
            HStack {
                TextField("成本", value: $service.cost, format: .currency(code: "CNY"))
                ClearButtonView(value: $service.cost)
            }
            
            HStack {
                TextField("里程", value: $service.mileage, format: .number)
                ClearButtonView(value: $service.mileage)
            }
        }
        .padding()
        .textFieldStyle(.roundedBorder)
    }
}

设计思路说明

  • 采用单个属性绑定而非整个模型:避免视图与Servicing强耦合,让ClearButtonView可以复用在任何需要清除Numeric类型绑定值的场景中。
  • 泛型+Numeric约束:确保视图能处理Double、Int等所有支持数值运算的类型,同时保证0赋值的合法性。

内容的提问来源于stack exchange,提问作者David

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.30 21:12:42