SwiftUI:如何为文本添加自定义修饰符

SwiftUI: How to add custom modifier for Text

到目前为止,我可以为视图编写自定义修饰符;然而,当试图让我的代码保持干燥时,我试图为 TextFields 添加一个自定义修饰符。视图修饰符适用于类似这样的东西:

struct sampleModifier : ViewModifier {
    var height: CGFloat? = 100
    func body(content: Content) -> some View {
        content
            .frame(height: height)
            .background(Color.white)
            .border(Color.gray, width: 0.5)
            .shadow(color: Color.black, radius: 15, x: 0, y: 10)
    }
}

但是当我尝试使用 font 等修饰符时,它显示了很多错误。我知道他们可能需要更具体,而不是符合 TextFieldStyleModifier,但我不知道如何让它工作。我试过这样做但没有成功:

struct TitleModifier : TextFieldStyleModifier {
    func body(content: TextFieldStyle) -> some View {
        content
            .font(.custom("Open Sans", size: 18))
            .color(Color.green)

    }
}

这显然失败并显示以下错误:

如果我点击 Fix 建议,它会将其添加到我的代码中

TextFieldStyleModifier<<#Style: TextFieldStyle#>>

不知道怎么用

有什么建议吗?

TextField 也是视图,因此您可以用同样的方式创建修饰符:

struct TitleModifier : ViewModifier {
    func body(content: Content) -> some View {
        content
            .font(.custom("Open Sans", size: 18))
            .foregroundColor(Color.green)

    }
}

另请注意,没有修饰符 .color()。它是.foregroundColor()。

当您想将它应用到 FormField 时,您只需:

TextField("", text: $field1).modifier(TitleModifier())

Xcode 11 beta 4 中,color(_:) 修饰符已弃用。因此,请改用 foregroundColor(_:) 方法。

您可以创建自定义 TextFieldStyle,这将仅适用于 TextField,不适用于视图容器中的其他视图

struct CustomTextFieldStyle: TextFieldStyle {
    func _body(configuration: TextField<Self._Label>) -> some View {
        configuration
            .font(.custom("Open Sans", size: 18))
            .foregroundColor(Color.green)
    }
}

用法:

Group {
    Text("not applied here")
    TextField("applied here", text: $presenter.name)
}
.textFieldStyle(CustomTextFieldStyle())

现在可以将 .font().foregroundColor() 修饰符添加到 ViewModifier 中的 content。但是,如果您想添加一些只能应用于特定视图的自定义修饰符,例如文本视图的 .strikethrough() 修饰符,您可以将这些修饰符添加到扩展中。

struct TitleModifier: ViewModifier {
    func body(content: Content) -> some View {
        content
            .font(.custom("Open Sans", size: 18))
            .foregroundColor(.green)
    }
}

extension Text {
    func customText() -> some View {
        self.strikethrough().bold().italic().lineLimit(4)
            .modifier(TitleModifier())
    }
}

用法Text("Hello").customText().