Skip to content

Instantly share code, notes, and snippets.

@peterkos
Created May 25, 2024 23:33
Show Gist options
  • Save peterkos/91bbb501273c9f54ef5a4d5b3c7b1273 to your computer and use it in GitHub Desktop.
Save peterkos/91bbb501273c9f54ef5a4d5b3c7b1273 to your computer and use it in GitHub Desktop.
Apply a background to all cells in a GridRow, with rounded corners.
/// 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