主页 Swift UNIX C Assembly Go Plan 9 Web MCU Research Non-Tech

How to obatin the size of a View in SwiftUI

2022-01-20 | Swift | #Words: 324

In some cases, we may need to obtain the size of a View in SwiftUI. We can obtain it using the following method:

.overlay(GeometryReader { geo -> AnyView in
                    DispatchQueue.main.async{
                        self.displayWidth = geo.size.width
                        self.displayHeight = geo.size.height
                    }
                    return AnyView(EmptyView())
            })

Let me give you an example: Obtain the size of Text View:

struct ContentView: View {
    @State private var displayWidth: CGFloat = 0
    @State private var displayHeight: CGFloat = 0
    @State private var widthAndHeight = ""
    var body: some View {
        VStack {
            Text("Hello, world!")
                .padding()
                .overlay(GeometryReader { geo -> AnyView in
                    DispatchQueue.main.async{
                        displayWidth = geo.size.width
                        displayHeight = geo.size.height
                        widthAndHeight = geo.size.debugDescription
                    }
                    return AnyView(EmptyView())
            })
            Text("宽度:\(displayWidth)")
            Text("高度:\(displayHeight)")
            Text("宽高:\(widthAndHeight)")
        }
    }
}

The page looks like

The size of View

Notice: the size includes padding, if the size of component attached to View exceeds View’s size, it also include the exceeded part.

I hope these will help someone in need~