5

I am trying to create this modifier:

struct CustomTextBorder: ViewModifier {
    func body(content: Content) -> some View {
        return content
            .font(.largeTitle)
            .padding()
            .overlay(
                RoundedRectangle(cornerRadius: 15)
                    .stroke(lineWidth: 2)
            )
            .foregroundColor(.blue)
    }
}

When I do, I get Type 'CustomTextBorder' does not conform to protocol 'ViewModifier' error.

It seems like I have to add:

typealias Body = <#type#>

However, I see modifiers being created as I originally did here without having to provide the typealias Body...

This modifier works here:

https://www.simpleswiftguide.com/how-to-make-custom-view-modifiers-in-swiftui/

Why isn't it working for me?

How can I make this modifier work? Why does it work for some and not for others? Does it depend on what the project targets? I am targeting iOS 15.

1
  • This code works fine to me. Commented Aug 10, 2021 at 20:30

2 Answers 2

4

Without seeing your implementation, it looks like your not initializing the modifier. Be sure you're using the braces at the end CustomTextBorder(). Remember, it's still a function that needs to be called.

Text("SwiftUI Tutorials")
  .modifier(CustomTextBorder())

Same if you're making an extension of View

extension View {
  func customTextBorder() -> some View {
    return self.modifier(CustomTextBorder())
  }
}
Sign up to request clarification or add additional context in comments.

1 Comment

The error message has changed slightly, it now says CustomTextBorder.Type ... and in retrospect, it's abundantly clear. Pass the type, it won't work, pass an instance, it does.
0

Your code works fine, but why ViewModifier? you do not need ViewModifier for this simple thing, you can use extension in this way:

struct ContentView: View {
    
    var body: some View {

        Text("Hello, World!").customTextBorder
        
    }
    
}



extension Text {
    
    var customTextBorder: some View {
        
        return self
            .font(.largeTitle)
            .padding()
            .overlay(
                RoundedRectangle(cornerRadius: 15)
                    .stroke(lineWidth: 2)
            )
            .foregroundColor(.blue)
        
    }
    
}

enter image description here

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.