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

有些话、适合烂在心里 提交于 2019-12-08 09:45:52

问题


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)


回答1:


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)
    }
}


来源:https://stackoverflow.com/questions/58281687/how-to-set-height-and-width-in-proportion-with-superview-in-swiftui

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!