1

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.

1 Answer 1

3

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)
    }
}
Sign up to request clarification or add additional context in comments.

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.