Picker只有在与Int一起使用时才能正常工作,当使用任何其他类型的BinaryInteger时,它根本不会更新 Select .为了纠正这一点,我想做CompatilibityPicker,但我必须承认,我对Binding实际工作原理的理解给我带来了很多麻烦.以下是我当前的代码:

struct CompatibilityPicker<Label, SelectionValue, Content> : View where Label : View, SelectionValue : BinaryInteger, Content : View {

    var content : () -> Content
    var label : Label

    @Binding var _selection : SelectionValue

    var selection : Int {
        get {
            Int(_selection)
        }
        set {
            self._selection = SelectionValue(newValue)
        }
    }

    var body: some View {
        // This line shows errors about selection and I don't know how to fix them,
        // using $selection does not work either.
        Picker(label, selection: selection, content: content)
    }
}

推荐答案

这里是固定变量分离的外部绑定和内部代理绑定来进行转换

struct CompatibilityPicker<Label, SelectionValue, Content>: View where Label : View, SelectionValue : BinaryInteger, Content : View {

    var content : () -> Content
    var label : Label

    @Binding var selection : SelectionValue

    private var value: Binding<Int> { Binding<Int>(
        get: {
            Int(selection)
        },
        set: {
            self.selection = SelectionValue($0)
        })
    }

    var body: some View {
        Picker(selection: value, content: content) { label }
    }
}

Swift相关问答推荐

有没有一种方法可以迭代可编码的代码(例如,JSON解析中的每一项)?

了解SWIFT中的任务行为

Swift图表';chartXVisibleDomain挂起或崩溃

如何在visionOS中将模型锚定在用户头部上方?

如何将变量添加到不属于可解码部分的 struct ?

使用 WrappingHStack 文本溢出到新行

Swift 根据总值将数组拆分为块

如何在 Swift 中的两个 UIView 中心之间添加线?

如何根据 SwiftUI 中的字体大小定义按钮的大小?

在 Swift 5.5 中编写同步和异步函数

将阻塞函数集成到 Swift 异步中

.onTapGesture 不适用于 Stepper,仅适用于其文本

在 Swift 中将两个字节的 UInt8 数组转换为 UInt16

try 在解除分配时加载视图控制器的视图... UIAlertController

修复 Swift 3 中的警告C-style for Statement is deprecated

强制打开已在同一行代码中 Select 性访问的变量是否安全?

WKWebView 确实从本地文档文件夹加载资源

如何判断 firebase 数据库值是否存在?

静态成员不能用于类型的实例

'self' 在所有存储的属性被初始化之前使用