Get width of a view using in SwiftUI

前端 未结 2 1832
时光取名叫无心
时光取名叫无心 2020-12-29 09:27

I need to get width of a rendered view in SwiftUI, which is apparently not that easy.

The way I see it is that I need a function that returns a view\'s d

2条回答
  •  借酒劲吻你
    2020-12-29 10:11

    The only way to get the dimensions of a View is by using a GeometryReader. The reader return the dimensions of the container.

    What is a geometry reader? the documentation says:

    A container view that defines its content as a function of its own size and coordinate space. Apple Doc

    So you could get the dimensions by doing this:

    struct ContentView: View {
    
       @State var frame: CGSize = .zero
    
        var body: some View {
            HStack {
                GeometryReader { (geometry) in
                    self.makeView(geometry)
                }
            }
    
        }
    
        func makeView(_ geometry: GeometryProxy) -> some View {
            print(geometry.size.width, geometry.size.height)
    
            DispatchQueue.main.async { self.frame = geometry.size }
    
            return Text("Test")
                    .frame(width: geometry.size.width)
        }
    }
    

    The printed size is the dimension of the HStack that is the container of inner view.

    You could potentially using another GeometryReader to get the inner dimension.

    But remember, SwiftUI is a declarative framework. So you should avoid calculating dimensions for the view:

    read this to more example:

    • Make a VStack fill the width of the screen in SwiftUI
    • How to make view the size of another view in SwiftUI

提交回复
热议问题