History
Loading...
Loading...
September 19, 2025
.overlay(alignment:) instead of ZStack when you need to add decorative elements like badges, indicators, or watermarks to existing views. The overlay modifier maintains the original view's frame while adding content on top with precise alignment control.Using overlay with specific alignment keeps the base view's sizing logic intact while adding contextual elements. The overlay doesn't affect the original view's layout calculations, making it perfect for badges, notifications, or decorative elements that shouldn't impact the underlying content structure.
struct ProductCard: View {
let product: Product
let isOnSale: Bool
var body: some View {
VStack {
AsyncImage(url: product.imageURL) { image in
image
.resizable()
.aspectRatio(contentMode: .fill)
} placeholder: {
Color.gray.opacity(0.3)
}
.frame(height: 200)
.clipped()
.overlay(alignment: .topTrailing) {
if isOnSale {
Text("SALE")
.font(.caption.bold())
.foregroundColor(.white)
.padding(.horizontal, 8)
.padding(.vertical, 4)
.background(Color.red)
.clipShape(RoundedRectangle(cornerRadius: 4))
.offset(x: -8, y: 8)
}
}
Text(product.name)
.font(.headline)
.lineLimit(2)
}
}
}This approach is cleaner than ZStack because it maintains semantic clarity - the base view defines the size and the overlay adds visual enhancements. It also prevents layout issues that can occur when ZStack children have competing size requirements, and makes the code more maintainable by clearly separating primary content from supplementary UI elements.