Home > Net >  Ternary for clipShape swift
Ternary for clipShape swift

Time:07-14

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

CodePudding user response:

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()
}
}

}

CodePudding user response:

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))
    }
}
  • Related