Created
October 20, 2025 12:31
-
-
Save dterekhov/4a76ea9a4afca8c89f9ee7fd88303654 to your computer and use it in GitHub Desktop.
New containerRelativeFrame - replacement older frame(maxWidth: .infinity) #swiftui
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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() } |
Author
dterekhov
commented
Oct 22, 2025


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