skip to Main Content

I have a rectangle in a frame as shown below

Rectangle in iPhone 13

Rectangle in iPhone 8

I am trying to proportionally adjust the height of rectangle so that there is an equal proportion of white in every iPhone model, but as is clearly visible the rectangle takes over the entire screen in a smaller iPhone model.

I am sure SwiftUI has a formal feature that allows for the rectangle to be resized proportionally.

How can I do this? Code shown below


         VStack {
            ZStack {
                //Rectangle 12
                Rectangle()
                    .fill(Color(#colorLiteral(red: 0.7137255072593689, green: 0.10196077823638916, blue: 0.10196077823638916, alpha: 1)))
                    .frame(width: 391, height: 800)
                
                
            }
            
            Spacer()
            
        }.ignoresSafeArea(edges: .top)

EDIT: It seems like my question, while describing what I want in isolation did not truly encapsulate what I want

I want to create this design

enter image description here

However, I want it to scale properly across devices.

How would I go about doing this?

2

Answers


  1. This is exactly what a GeometryReader is for. It reads the size given to it, in this case the whole screen. Then, you can put a .frame() on the Spacer which is a compressible view to keep it at a set size. In the example code below, it is 10% of the view height.

    struct ProportionalRectangle: View {
        var body: some View {
            GeometryReader { geometry in
                VStack {
                    Rectangle()
                        .fill(Color(#colorLiteral(red: 0.7137255072593689, green: 0.10196077823638916, blue: 0.10196077823638916, alpha: 1)))
                    Spacer()
                        .frame(height: geometry.size.height * 0.1)
                }
            }
            .ignoresSafeArea()
        }
    }
    
    Login or Signup to reply.
  2. Do you mean you want to divide the view into red rectangle and white.

    struct ContentView: View {
        var body: some View {
            VStack {
                Rectangle()
                    .fill(.red)
                    .frame(maxWidth: .infinity, maxHeight: .infinity)
                Rectangle()
                    .fill(.white)
                    .frame(maxWidth: .infinity, maxHeight: .infinity)
            }.ignoresSafeArea()
        }
    }
    

    enter image description here

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