SwiftUI: How to add custom modifier for Text
TextFields are also views, so you create the modifier in the same fashion:
struct TitleModifier : ViewModifier {
func body(content: Content) -> some View {
content
.font(.custom("Open Sans", size: 18))
.foregroundColor(Color.green)
}
}
Also note that there is no modifier .color(). It is .foregroundColor().
When you want to apply it to a FormField, you just do:
TextField("", text: $field1).modifier(TitleModifier())
Right now it is possible to add .font()
and .foregroundColor()
modifiers to the content
inside ViewModifier. However, if you want to add some custom modifiers that can be applied only to a specific view, for example .strikethrough()
modifier for Text View, you can add these modifiers into the extension.
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())
}
}
Usage Text("Hello").customText()
.
In Xcode 11 beta 4, the color(_:)
modifier is deprecated. So use the foregroundColor(_:)
method instead.
You can create a custom TextFieldStyle, this will apply only to TextField, not to other views on the view container
struct CustomTextFieldStyle: TextFieldStyle {
func _body(configuration: TextField<Self._Label>) -> some View {
configuration
.font(.custom("Open Sans", size: 18))
.foregroundColor(Color.green)
}
}
Usage:
Group {
Text("not applied here")
TextField("applied here", text: $presenter.name)
}
.textFieldStyle(CustomTextFieldStyle())