【问题标题】:How to set up Binding of computed value inside class (SwiftUI)如何在类内设置计算值的绑定(SwiftUI)
【发布时间】:2021-11-23 19:50:29
【问题描述】:

在我的模型中,我有一个 Items 数组和一个计算属性 proxy,它使用 set{} 和 get{} 在数组中设置和返回当前选定的项目并用作快捷方式。手动将项目的值设置为model.proxy?.value = 10 有效,但无法弄清楚如何使用 $ 将此值绑定到组件。

import SwiftUI

struct Item {
    var value: Double
}

class Model: ObservableObject {
    @Published var items: [Item] = [Item(value: 1), Item(value: 2), Item(value: 3)]
    
    var proxy: Item? {
        get {
            return items[1]
        }
        set {
            items[1] = newValue!
        }
    }
}

struct ContentView: View {
    @StateObject var model = Model()
    var body: some View {
        VStack {
            Text("Value: \(model.proxy!.value)")
            
            Button(action: {model.proxy?.value = 123}, label: {Text("123")}) // method 1: this works fine
            SubView(value: $model.proxy.value) // method 2: binding won't work
        }.padding()
    }
}

struct SubView <B:BinaryFloatingPoint> : View {
    @Binding var value: B
    var body: some View {
        Button( action: {value = 100}, label: {Text("1")})
    }
}

有没有办法修改proxy,使其可修改和可绑定,以便两种方法都可用?

谢谢!

第 2 天:绑定

感谢 George,我已经成功设置了 Binding,但所需的 SubView 绑定仍然无法正常工作。代码如下:

import SwiftUI

struct Item {
    var value: Double
}

class Model: ObservableObject {
    @Published var items: [Item] = [Item(value: 0), Item(value: 0), Item(value: 0)]
    
    var proxy: Binding <Item?> {
        Binding <Item?> (
            get: { self.items[1] },
            set: { self.items[1] = $0! }
        )
    }
}

struct ContentView: View {
    @StateObject var model = Model()
    @State var myval: Double = 10
    var body: some View {
        VStack {
            Text("Value: \(model.proxy.wrappedValue!.value)")
            Button(action: {model.proxy.wrappedValue?.value = 555}, label: {Text("555")})
            SubView(value: model.proxy.value) // this still wont work
        }.padding()
    }
}

struct SubView <T:BinaryFloatingPoint> : View {
    @Binding var value: T
    var body: some View {
        Button( action: {value = 100}, label: {Text("B 100")})
    }
}

【问题讨论】:

  • 首先我不明白为什么绑定是可选的,因为您使用的是硬编码索引,因此您要么总是得到一个对象,要么总是会崩溃。其次,由于您的子视图是通用的,您需要传递类型 SubView&lt;Double&gt;(value: model.proxy.value)
  • @JoakimDanielson 索引带有条形码是为了使示例代码更短。至于 Double 我正在尝试制作一个接受 CGFloat、Double 和 Int 的组件,所以我使用 BinaryFloatingPoint。但还不确定如何处理 BinaryFloatingPoint。
  • 好的,但你试过我的代码了吗?对我来说这行得通。

标签: swift class object binding


【解决方案1】:

改为创建Binding

例子:

var proxy: Binding<Item?> {
    Binding<Item?>(
        get: { items[1] },
        set: { items[1] = $0! }
    )
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-06-30
    • 2017-06-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-30
    相关资源
    最近更新 更多