4

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.

zumzum
  • 17,984
  • 26
  • 111
  • 172

2 Answers2

3

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())
  }
}
D. Greg
  • 991
  • 1
  • 9
  • 21
  • 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. – green_knight Apr 16 '22 at 23:29
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

ios coder
  • 1
  • 4
  • 31
  • 91