Search code examples
iosswiftxcodeswiftuixcode11

How to set height and width in proportion with superview in SwiftUI?


I want to know that is it possible to adjust height and width in proportion according to superview in SwiftUI to any UIControl ?

As we are doing like :

let txtFld = UITextField()
txtFld.frame = CGRect(origin: CGPoint(x: 0, y: 0), size: CGSize(width: self.view.frame.width/2, height: self.view.frame.height*0.1))

I know we can somehow achieve to adjust width by using Spacer(), .padding and edgeInsets. But what about height? I have seen lots of tutorial for SwiftUI, everywhere height is static. Even on Apple's site. SwiftUI Tutorials

If anyone have knowledge about how to set height in proportion with view's height, please share here. Because at some point we need like that. For ex. If it needs to make button according to device height. (Let's say in iPhone SE = 40, iPhone 8P = 55, iPhone X = 65)


Solution

  • You can use GeometryReader to get that information from the parent:

    struct MyView: View {
        var body: some View {
            GeometryReader { geometry in
               /*
                 Implement your view content here
                 and you can use the geometry variable
                 which contains geometry.size of the parent
                 You also have function to get the bounds
                 of the parent: geometry.frame(in: .global)
               */
            }
        }
    }
    

    You can have a custom struct for you View and bind it's geometry to a variable to make it's geometry accessible from out of the View itself.

    - Example:

    First define a view called GeometryGetter (giving credit to @kontiki):

    struct GeometryGetter: View {
        @Binding var rect: CGRect
    
        var body: some View {
            return GeometryReader { geometry in
                self.makeView(geometry: geometry)
            }
        }
    
        func makeView(geometry: GeometryProxy) -> some View {
            DispatchQueue.main.async {
                self.rect = geometry.frame(in: .global)
            }
    
            return Rectangle().fill(Color.clear)
        }
    }
    

    Then, to get the bounds of a Text view (or any other view):

    struct MyView: View {
        @State private var rect: CGRect = CGRect()
    
        var body: some View {
            Text("some text").background(GeometryGetter($rect))
    
            // You can then use rect in other places of your view:
            Rectangle().frame(width: 100, height: rect.height)
        }
    }