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.
You can use containerRelativeFrame(_:alignment:)
as such:
struct MyView: View {
var body: some View {
Rectangle()
.containerRelativeFrame(.vertical) { height, _ in
height * 0.35
}
.overlay {
Text("Rectangle with height equal to 35% of its container")
.foregroundStyle(.black)
}
}
}
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(.black)
}
.frame(height: proxy.size.height * 0.35)
}
}
}