Search code examples
swiftinheritanceconstraintswidthswiftui

How to access parents frame in SwiftUI


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?


Solution

  • 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.