SwiftUI textFieldStyle 修饰符 RoundedBorderTextFieldStyle 和 PlainTextFieldStyle 之间的类型不匹配

Type mismatch between SwiftUI textFieldStyle modifiers RoundedBorderTextFieldStyle and PlainTextFieldStyle

我正在尝试根据我的 View 是否正在编辑来更改 TextField.textFieldStyle 修饰符。我声明 var isEditing: Bool,在父 View 中设置它并在 body 中检查它。我的代码:

TextField("Type a Name", text: $name) {
    myManagedObjectObserved.attribute = name
}
.textFieldStyle(isEditing ? RoundedBorderTextFieldStyle() : PlainTextFieldStyle())

编译器抱怨以下构建时错误...

Result values in '? :' expression have mismatching types 'RoundedBorderTextFieldStyle' and 'PlainTextFieldStyle'

不明白为什么?有人能解释一下吗?

它们是不同的类型,因此swift类型检查报告错误。

这是可能的解决方案(使用 Xcode 12 测试)

@ViewBuilder
var body: some View {
    if isEditing {
        TextField("Type a Name", text: $name) {
            myManagedObjectObserved = name
        }
        .textFieldStyle(RoundedBorderTextFieldStyle())
    } else {
        TextField("Type a Name", text: $name) {
            myManagedObjectObserved = name
        }
        .textFieldStyle(PlainTextFieldStyle())
    }
}

更新:更方便的变体(具有相同的想法)

extension TextField {
    @ViewBuilder
    func editingStyle(if flag: Bool) -> some View {
        if flag {
            self.textFieldStyle(RoundedBorderTextFieldStyle())
        } else {
            self.textFieldStyle(PlainTextFieldStyle())
        }
    }
}

struct TestView: View {
    @State private var name = ""
    @State private var isEditing = false

    @ViewBuilder
    var body: some View {
        TextField("Type a Name", text: $name) {
            myManagedObjectObserved = name
        }
        .editingStyle(if: isEditing)
    }
}