swiftswiftuiswiftui-state

SwiftUI - Change View variable based on input parameter


How do I change the @State variable size in a view based on the input parameter categorySize supplied when calling the view?

I'd like to change the size to 140 when categorySize == .Large and to 40 when categorySize == .Small.

enum ExampleEnum {
     case Large
     case Small
}

struct TestView: View {

   let categorySize: ExampleEnum
   @State private var size: CGFloat = 92

   var body: some View {
   Image(name: "TestImage")
      .resizable()
      .frame(width: size, height: size)
   }
}

TestView(categorySize: .Small)

I tried via an if-statement but this doesn't do the trick:

struct TestView: View {

   let categorySize: ExampleEnum
   @State private var size: CGFloat = 92

   var body: some View {

   if categorySize == .Large {      <=== Not working
      $size = 140
   } else if categorySize == .Small {
      $size = 40
   }

   Image(name: "TestImage")
      .resizable()
      .frame(width: size, height: size)
   }
}

I am aware that I can pass the size parameter when calling the view. However, I'd like to only pass the categorySize and then have a view logic handle the size variable within the view.


Solution

  • Here is possible approach

    struct TestView: View {
        
        let categorySize: ExampleEnum
        
        var body: some View {
            
            var size: CGFloat  = 92
            if categorySize == .Large {
                size = 140
            } else if categorySize == .Small {
                size = 40
            }
            
            return Image(name: "TestImage")
                .resizable()
                .frame(width: size, height: size)
        }
    }