如何在 SwiftUI 中将布尔表达式转换为 Binding

2024-03-20

我有一个文本字段,当用户输入特定字符串时我试图转到另一个视图。

import SwiftUI

struct ContentView: View {
    @State var whether_go = "No"
    var body: some View {
                    TextField("Goto?", text: $whether_go)
                        .navigate(to: CircleImage(), when: whether_go == "Yes")
    }
}

这会引发错误:Cannot convert value of type 'Bool' to expected argument type 'Binding<Bool>'因为when参数需要 Binding

我尝试使用

when: Binding<Bool>(get: whether_happy == "Yes"))

这会引发另一个错误:No exact matches in call to initializer.

那么我应该怎么做才能将布尔值转换为 Binding


您需要使用Binding(get:set:)初始化器。

var body: some View {
        let binding = Binding<Bool>(get: { self.whether_go == "YES" }, set: { if $0 { self.whether_go = "YES"} else { self.whether_go = "NO" }})
        return TextField("Goto?", text: $whether_go)
                        .navigate(to: CircleImage(), when: binding)
    }

如果你想要Binding要成为单向,只需传入一个空闭包即可set.

let binding = Binding<Bool>(get: { self.whether_go == "YES" }, set: { _ in })

与你的问题无关,但为什么whether_go a String而不是一个Bool?另外,您应该遵循 Swift 命名约定,即变量名称采用小驼峰命名法 (whetherGo).

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何在 SwiftUI 中将布尔表达式转换为 Binding? 的相关文章

随机推荐