4

Still working on SwiftUI, but I got a problem. I created an Image with a dynamic frame, and I want a label which needs to be half width of the image (e.g Image width = 300; Label width 150)

In UIKit I should code something like this:

Label.widthAnchor.constraint(image.widthAnchor, multiplier: 1/2).isActive = true

I tried something similar in SwiftUI:

Image(systemName: "j.circle.fill")
            .resizable()
            .frame(width: UIScreen.main.bounds.width, height: UIScreen.main.bounds.width)
        Text("Placeholder").frame(width: Image.frame.width/2, height: 30)

But this doesn't work.

What shall I do?

Vipera74
  • 227
  • 3
  • 17
  • 1
    Geometry Reader is a possible solution. Take a look into this thread. https://stackoverflow.com/questions/56729619/what-is-geometry-reader-in-swiftui – Md Shafiul Islam Jul 01 '19 at 11:48

1 Answers1

2

Why not setting hard sizes for both then :

Image(systemName: "j.circle.fill")
     .resizable()
     .frame(width: UIScreen.main.bounds.width, height: UIScreen.main.bounds.width)

Text("Placeholder")
     .frame(width: UIScreen.main.bounds.width/2, height: 30)

If you want to change the whole size of the component in one place you could just do it like this :

struct MyView : View {

     private var compWidth: CGFloat { UIScreen.main.bounds.width }

     var body: some View {
         VStack {
             Image(systemName: "j.circle.fill")
                   .resizable()
                   .frame(width: compWidth, height: compWidth)

             Text("Placeholder")
                   .frame(width: compWidth/2, height: 30)
         }
     }
}

Or, for a more elegant approach you could look into GeometryReader.

Bogdan Farca
  • 3,856
  • 26
  • 38