Skip to content

Instantly share code, notes, and snippets.

@dterekhov
Created October 20, 2025 12:31
Show Gist options
  • Select an option

  • Save dterekhov/4a76ea9a4afca8c89f9ee7fd88303654 to your computer and use it in GitHub Desktop.

Select an option

Save dterekhov/4a76ea9a4afca8c89f9ee7fd88303654 to your computer and use it in GitHub Desktop.
New containerRelativeFrame - replacement older frame(maxWidth: .infinity) #swiftui
import SwiftUI
// MARK: - 1. Basic fixed frame aligned to container
struct BasicsView: View {
var body: some View {
Color.red
.frame(width: 200, height: 300)
.containerRelativeFrame([.horizontal, .vertical], alignment: .topLeading)
}
}
#Preview { BasicsView() }
// MARK: - 2. Relative sizing depending on orientation
struct RelativeSizingView: View {
var body: some View {
Color.red
.containerRelativeFrame([.horizontal, .vertical]) { dimension, axis in
// Scale differently for portrait and landscape
if axis == .horizontal {
dimension * 2 / 3
} else {
dimension / 2
}
}
}
}
#Preview { RelativeSizingView() }
// MARK: - 3. Ratio-based sizing with ScrollView
struct MoreRelativeSizingView: View {
let ratio = 0.33
var body: some View {
ScrollView(.horizontal) {
HStack(spacing: 0) {
Color.green
.containerRelativeFrame(.horizontal) { dimension, _ in
dimension * ratio
}
Color.blue
.containerRelativeFrame(.horizontal) { dimension, _ in
dimension * (1 - ratio)
}
}
.padding()
.frame(height: 150)
}
}
}
#Preview { MoreRelativeSizingView() }
// MARK: - 4. Count and spacing based layout
struct CountAndSpanView: View {
let colors: [Color] = [.red, .green, .yellow, .blue, .cyan, .purple]
var body: some View {
ScrollView(.horizontal) {
LazyHStack {
ForEach(colors, id: \.self) { color in
color
.containerRelativeFrame(.horizontal, count: 4, spacing: 10)
}
}
.frame(height: 300)
}
}
}
#Preview { CountAndSpanView() }
// MARK: - 5. Image scroll view using span parameter
struct ImageScrollView: View {
var body: some View {
ScrollView(.horizontal) {
LazyHStack {
ForEach(1..<10, id: \.self) { index in
Image("image\(index)")
.resizable()
.aspectRatio(3 / 2, contentMode: .fit)
.containerRelativeFrame(.horizontal, count: 4, span: 3, spacing: 10)
}
}
.frame(height: 300)
}
}
}
#Preview { ImageScrollView() }
@dterekhov
Copy link
Author

F8EAC131-656C-4D41-9DC0-C4CBCC92B7AE_1_101_o
E58706C3-24B0-47FE-B384-A2C3798FF86D

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment