How to get the width of the view in SwiftUI?

by kyla.kuvalis , in category: Swift , a year ago

How to get the width of the view in SwiftUI?

Facebook Twitter LinkedIn Telegram Whatsapp

2 answers

by cassandra , a year ago

@kyla.kuvalis 

To get the width of a view in SwiftUI, you can use the frame(width:height:alignment:) modifier, which allows you to specify a fixed width and height for the view. For example:

1
2
3
4
5
6
struct MyView: View {
    var body: some View {
        Text("Hello, World!")
            .frame(width: 200, height: 50, alignment: .center)
    }
}


This will set the width of the Text view to 200 points.


Alternatively, you can use the GeometryReader view to dynamically size a view based on its parent's size. The GeometryReader provides a set of coordinates and dimensions for its child views, which you can use to set the size of your view. For example:

1
2
3
4
5
6
7
8
struct MyView: View {
    var body: some View {
        GeometryReader { geometry in
            Text("Hello, World!")
                .frame(width: geometry.size.width, height: 50, alignment: .center)
        }
    }
}


This will set the width of the Text view to the width of its parent view, as determined by the GeometryReader.


You can also use the .frame(minWidth:maxWidth:minHeight:maxHeight:alignment:) modifier to specify a range of valid width and height values for a view.

by reynold.dach , 4 months ago

@kyla.kuvalis 

Here's an example:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
struct MyView: View {
    var body: some View {
        Text("Hello, World!")
            .frame(minWidth: 0, maxWidth: .infinity, minHeight: 0, maxHeight: .infinity, alignment: .center)
            .background(GeometryReader { geometry in
                Color.clear // This view will take up the entire width of its parent
                    .preference(key: ViewWidthPreferenceKey.self, value: geometry.size.width)
            })
            .onPreferenceChange(ViewWidthPreferenceKey.self) { width in
                // Do something with the width value
                print("View width: (width)")
            }
    }
}


In this example, we use the .frame(minWidth:maxWidth:minHeight:maxHeight:alignment:) modifier with the minWidth and maxWidth set to 0 and .infinity respectively. This ensures that the view will take up the entire width of its parent.


We also use the GeometryReader to get the size of the view and store it in a preference key called ViewWidthPreferenceKey. We then use the .background() modifier to apply the GeometryReader to the text view and set the color to .clear so that it doesn't affect the visual appearance of the view.


Finally, we use the .onPreferenceChange() modifier to listen for changes in the ViewWidthPreferenceKey preference and print out the width value when it changes. You can replace the print statement with any logic you want to perform with the width value.