TextField的ViewModifier不符合ViewModifier的要求?

3

我在一个视图中有这段代码:

struct TextFieldClearButton: ViewModifier {

    @Binding var text: String

    func body(content: Content) -> some View {

        HStack {

            content

            if !text.isEmpty {
                Button(
                    action: { self.text = "" },
                    label: {
                        Image(systemName: "delete.left")
                            .foregroundColor(Color(UIColor.opaqueSeparator))
                    }
                )
            }
        }
    }
}

我遇到了两个错误:
  1. Type 'TextFieldClearButton' does not conform to protocol 'ViewModifier'(类型“TextFieldClearButton”不符合协议“ViewModifier”)
  2. Static method 'buildBlock' requires that 'Content' conform to 'View'(静态方法“buildBlock”要求“Content”符合“View”)
如何消除这些错误并使此修饰符编译通过呢?
看起来我根本不能使用ViewModifier。 添加非常简单的情况也会出错吗??
请参考以下图片:

enter image description here

enter image description here


它已经编译并在这里(Xcode 13.2)正常工作,可能是您的代码与其他代码存在命名冲突。 - Asperi
很奇怪,目前我看不到任何命名冲突。我正在运行Xcode 13.3版本(13E113)。 - zumzum
已重新测试通过 Xcode 13.3.1 / iOS 15.4 - 编译并正常运行。您使用的是哪个部署目标版本? - Asperi
2个回答

9
你的项目中很可能有一个名为“Content”的struct/class
如果你使用的是Xcode的标准深色主题,“薄荷绿”色表示它是“项目”定义的。

enter image description here

当您使用苹果的定义时,它是粉紫色的,就像您屏幕截图中的 ViewModifierViewString

enter image description here

搜索 struct Contentclass Contentenum Content 等相关内容。在您的项目中,您将找到重复项,然后只需更改重复项的名称即可。

它也可以是通用的 <Content: SomeProtocol><Content>typealias Content

您可以通过更具体地描述来确认重复项。

enter image description here


或者像这样声明 body 方法:func body(content: SwiftUI.Content) -> some View - rob mayoff
@robmayoff中的“Content”通常是一个通用的<Content: View>或者是一个typealias,它不是SwiftUI的一部分,所以SwiftUI.Content将无法工作。ViewModifier.Content可能会起作用,但为什么每次需要使用它(或其他内容)时都要进行补偿,而不是直接重命名副本呢?这似乎更有利于连续性。 - lorem ipsum
哎呀,是的,我应该说“ViewModifier.Content”,而不是“SwiftUI.Content”。 - rob mayoff

0

SwiftUI的错误真的很奇怪。在这种情况下,错误出现在Color构造函数中。将Color(UIColor.opaqueSeparator)更改为

Color(uiColor: UIColor.opaqueSeparator)


尝试过了,仍然不起作用。 - zumzum
你导入了UIKit吗? - TheLivingForce
是的,我导入了UIKit。 - zumzum

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接