SwiftUI - View Size



View size represent the height and width of the view. Using view size we can determine how much space does a view takes in its parent view, it helps developer how they will adjust multiple views in the parent view. We can control the width and height of the view separately. In SwiftUI, we can use either fixed size or dynamic size this is totally depends upon the choice of the developer.

Fixed Size in SwiftUI

Fixed size is a size which doesn't change. In SwiftUI, we can achieve using frame() modifier. This modifier control the size and width of the child view or the parent view. It is the most used and straightforward modifier to adjust the size of the view. Using this modifier we can either adjust width or height or both width and height. We can also set the alignment of the view with the help of frame() modifier.

Syntax

Following is the syntax −

func frame(
   width: CGFloat? = nil,
   height: CGFloat? = nil,
   alignment: Alignment = .center
) -> some View

Parameters

Following are the parameters supported by frame() modifier −

  • width: Used to set the fixed width.

  • height: Used to set the fixed height.

  • alignment: Used to set the alignment of the view.

Example

The following SwiftUI program set the width and height of the rectangle view.

import SwiftUI
struct ContentView: View {   
   var body: some View {
      ZStack{
         Rectangle()
            .fill(.orange)
         
         // Setting the width and height
            .frame(width: 250, height: 90)
         Text("TutorialsPoint")
            .font(.title2)
            .foregroundStyle(.white)
            .bold()
      }
   }
}
#Preview {
   ContentView()
}

Output

View Size

Dynamic Size in SwiftUI

In SwiftUI, we are allowed to specify the dynamic size of the view. This can achieve by using GeometryReader. GeometryReader is used to create a layout where the size of the child view is adjust according to the space available in parent view. It provide a geometry object which contains the size and position of the parent view, so we an get the size of child view by manipulating geometry object.

Syntax

Following is the syntax −

geometryReaderObject.size.width
geometryReaderObject.size.height

Example

The following SwiftUI program set the width and height of the rectangle view.

import SwiftUI
struct ContentView: View {   
   var body: some View {
      GeometryReader{myGeometry in
         VStack{
            Text("Width pf parent view: \(myGeometry.size.width)")
            Text("Height pf parent view: \(myGeometry.size.height)")
            
            Rectangle().fill(.mint)            
               // Dynamic sizes
               .frame(width: myGeometry.size.width/2, height: myGeometry.size.height/2)
         }
      }
   }
}
#Preview {
   ContentView()
}

Output

View Size
Advertisements