Created
May 25, 2024 23:33
-
-
Save peterkos/91bbb501273c9f54ef5a4d5b3c7b1273 to your computer and use it in GitHub Desktop.
Apply a background to all cells in a GridRow, with rounded corners.
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
/// Apply a background to all cells in a GridRow, with rounded corners. | |
/// | |
/// Example: | |
/// ```swift | |
/// Grid(/* ... */) { | |
/// ForEach(...) { element in | |
/// GridRow(alignment: .center) { | |
/// Text(element.title) | |
/// .modifier(FilledBackgroundModifier( | |
/// selected: element == selectedElement, // some @State property | |
/// position: .start | |
/// )) | |
/// } | |
/// } | |
/// } | |
/// ``` | |
struct FilledBackgroundModifier: ViewModifier { | |
var selected: Bool | |
var position: CellPosition = .middle | |
/// .start/.end used to determine if corners are drawn. | |
enum CellPosition { | |
case start, middle, end | |
} | |
func body(content: Content) -> some View { | |
content | |
.padding(.vertical, 10) | |
.padding(.trailing, 20) | |
.padding(.leading, position == .start ? 10 : 0) | |
.frame( | |
minWidth: 100, | |
maxWidth: .infinity, | |
maxHeight: .infinity, | |
alignment: .leading | |
) | |
.background( | |
shapeWithPositionalCorners | |
.fill(selected ? .blue : .clear) | |
) | |
} | |
private var shapeWithPositionalCorners: UnevenRoundedRectangle { | |
var radii = RectangleCornerRadii() | |
let radius = 8 | |
switch position { | |
case .start: | |
radii.topLeading = radius | |
radii.bottomLeading = radius | |
case .end: | |
radii.topTrailing = radius | |
radii.bottomTrailing = radius | |
default: break | |
} | |
return UnevenRoundedRectangle(cornerRadii: radii) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment