swiftswiftuilayoutuiscreen

Is it reasonable to use percentages with UIScreen Height?


Is it reasonable to use percentages with UIScreen Height to make auto layout in SwiftUi? I am quite new to Swift and I need to make an auto layout but as I know SwiftUI doesn’t have margins as UIKit. So I usually use height and width with percentages to make layout flexible for all iPhones. But I think that it is a bad option and hope that better ones exist.


Solution

  • If you want to make your views size adapt to their container, you can use GeometryReader like this:

    struct ContentView: View {
        var body: some View {
            GeometryReader { proxy in
                Rectangle()
                    .overlay { 
                        Text("Rectangle with height equal to 35% of its container")
                            .foregroundStyle(Color.black)
                    }
                .frame(height: proxy.size.height * 0.35)
            }
        }
    }
    

    result of provided code example