How to Retrieve the Dimensions of a View

Get width of a view using in SwiftUI

The only way to get the dimensions of a View is by using a GeometryReader. The reader returns 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

Determining the size of an Android view at runtime

Based on @mbaird's advice, I found a workable solution by subclassing the ImageView class and overriding onLayout(). I then created an observer interface which my activity implemented and passed a reference to itself to the class, which allowed it to tell the activity when it was actually finished sizing.

I'm not 100% convinced that this is the best solution (hence my not marking this answer as correct just yet), but it does work and according to the documentation is the first time when one can find the actual size of a view.

View's getWidth() and getHeight() returns 0

You are calling getWidth() too early. The UI has not been sized and laid out on the screen yet.

I doubt you want to be doing what you are doing, anyway -- widgets being animated do not change their clickable areas, and so the button will still respond to clicks in the original orientation regardless of how it has rotated.

That being said, you can use a dimension resource to define the button size, then reference that dimension resource from your layout file and your source code, to avoid this problem.

How can I get the dimensions of the view outside a function?

I'm not sure what exactly you're trying to do, but couldn't you just put this at the global level (i.e. above "class ViewController..."):

let screenWidth = UIScreen.mainScreen().bounds.size.width
let screenHeight = UIScreen.mainScreen().bounds.size.height

Then you can access these anywhere in your project.



Related Topics



Leave a reply



Submit