skip to Main Content

I want to display a View in the top 1/3 of the screen. In order to do so, I manipulate it as so:

var body: some View {
 VStack{
  Spacer()
  Text("I like chipotle")
  Spacer()
  Spacer()
 }
}

While that works for smaller examples, I wonder if there is a more declarative way to do this so if I for example want to put a view in the top 1/6 of a screen? I think about flex box where you can set the flex value of specific children to make them take up different percentages.

2

Answers


  1. Maybe you mean something like this:

    struct ContentView: View {
    
        let partOfScreen: CGFloat = 1/3
    
        var body: some View {
            GeometryReader { geo in
                VStack(spacing: 0) {
                    Text("I like chipotle")
                        .padding(.top, geo.size.height * partOfScreen)
                    Spacer(minLength: 0)
                }
            }
        }
    }
    

    You can add .ignoresSafeArea(.all) on GeometryReader if the entire screen area is needed

    Login or Signup to reply.
  2. No need for any Spacer You can directly assign the size to a view relative to its parent using the GeometryReader:

    GeometryReader { proxy in
        Text("I like Chipotle")
            .frame(height: proxy.size.height/3.rounded())
        }
    }
    

    💡 Quick Tip

    Always try to round position and size values. Otherwise, it will heavily impact the render engine to render fractional pixels and you may experience lags and drop frames.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search