【问题标题】:Swift error, Cannot convert value of type 'Binding<String?>' to expected argument type 'Binding<String>'Swift 错误,无法将 'Binding<String?>' 类型的值转换为预期的参数类型 'Binding<String>'
【发布时间】:2020-11-14 00:46:26
【问题描述】:

我有以下代码:

@State var message: String = ""

var body: some View {
        VStack {
            ZStack(alignment: .topLeading) {
                TextEditor(text: Binding($message))
                    .frame(minHeight: 30, alignment: .leading)
                    .cornerRadius(6.0)
                    .multilineTextAlignment(.leading)
                Text(message ?? "Message")
                    .padding(.leading, 4)
                    .opacity(message == "" ? 1 : 0)
                }
                .font(.body)
        }
    }
}

当我尝试执行代码时,它会在 TextEditor(text: Binding($message) 旁边显示 "Cannot convert value of type 'Binding&lt;String?&gt;' to expected argument type 'Binding&lt;String&gt;'" 为什么会出现此错误?

【问题讨论】:

  • 删除Binding()。只需使用TextEditor(text: $message)

标签: swift swiftui


【解决方案1】:

错误源于此行

Text(message ?? "Message")

因为编译器试图推断类型并且这一行显示类型应该是可选的,但编辑器期望不是可选的,所以你遇到了冲突和错误。您的message 状态不是可选的,因此您只需要直接在初始化程序中移动默认值即可。

这里是更正的变体:

struct DemoView: View {
    @State var message: String = "Message"
    
    var body: some View {
        VStack {
            ZStack(alignment: .topLeading) {
                TextEditor(text: $message)
                    .frame(minHeight: 30, alignment: .leading)
                    .cornerRadius(6.0)
                    .multilineTextAlignment(.leading)
                Text(message)
                    .padding(.leading, 4)
                    .opacity(message == "" ? 1 : 0)
            }
            .font(.body)
        }
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-12-30
    • 2021-09-09
    • 1970-01-01
    • 1970-01-01
    • 2023-01-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多