skip to Main Content

I am trying to pick a clipShape based on a boolean value.

.clipShape(
        noText ? Circle() : Capsule()
)

this will not work because of this error:

Result values in '? :' expression have mismatching types 'Circle' and 'Capsule'

What is the best way to accomplish selecting a clip-shape based on a boolean value? Thanks

2

Answers


  1. Your ? : expression need to ensure that both conditions are the same type, so to solve your problem just wrap your shape inside AnyShape(). Try below sample code(you can replace with your own image):

    import SwiftUI
    
    struct Practice: View {
    @State private var test = false
    var body: some View {
    Image(systemName: "rectangle.fill")
        .resizable()
        .padding()
        .clipShape(test ? AnyShape(Circle()) : AnyShape(Capsule()))
        //For iOS 14 this can be done with .mask
        //.mask(test ? AnyView(Circle()) : AnyView(Capsule()))
    Button("change shape") {
        test.toggle()
    }
    }
    
    }
    
    Login or Signup to reply.
  2. Here’s a possible solution using custom modifier:

    struct ContentView: View {
        @State private var noText = false
        var body: some View {
            Image("example").resizable().myClipShape(noText: noText)
        }
    }
    
    
    struct myModifier: ViewModifier {
        var noText: Bool
        func body(content: Content) -> some View {
            VStack{
                if noText {
                    content.clipShape(Circle())
                } else {
                    content.clipShape(Capsule())
                }
            }
           
        }
    }
    
    extension View {
        func myClipShape(noText: Bool) -> some View {
            modifier(myModifier(noText: noText))
        }
    }
    

    To create a custom modifier, first create a struct that conforms to ViewModifier. The ViewModifier protocol requires one thing which is the struct to have this method: func body(content: Content) -> some View. Inside the method, you can customize your custom modifier.

    Then you can use your custom modifier like this:

    Image("example").resizable().modifier(myModifier(noText: noText))
    

    But if you’re planning to use frequently, you can add it to the View Extension and use it like this too:

    Image("example").resizable().myClipShape(noText: noText)
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search