Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save jayesh15111988/6013f798c8a8ccfc0f21c016a3a69703 to your computer and use it in GitHub Desktop.
Save jayesh15111988/6013f798c8a8ccfc0f21c016a3a69703 to your computer and use it in GitHub Desktop.
A source code to demonstrate how to apply rounded corner, rounded borders and shadow to a SwiftUI view
// An utility view extension
extension View {
@ViewBuilder
func `if`<Transform: View>(_ condition: Bool, transform: (Self) -> Transform) -> some View {
if condition { transform(self) }
else { self }
}
}
// View modifier implementation
struct RoundedCornerWithShadowModifier: ViewModifier {
let contentPadding: CGFloat
let cornerRadius: CGFloat
let isShadow: Bool
let borderColor: Color
let borderWidth: CGFloat
init(contentPadding: CGFloat = 12.0, cornerRadius: CGFloat, isShadow: Bool = false, borderColor: Color, borderWidth: CGFloat) {
self.contentPadding = contentPadding
self.cornerRadius = cornerRadius
self.isShadow = isShadow
self.borderColor = borderColor
self.borderWidth = borderWidth
}
func body(content: Content) -> some View {
content
.padding(contentPadding)
.background(
RoundedRectangle(cornerRadius: cornerRadius)
.fill(Color.green)
.if(isShadow) { $0.shadow(color: Color.black.opacity(0.5), radius: 12, x: 0, y: 0)
}
)
.overlay(
RoundedRectangle(cornerRadius: cornerRadius)
.stroke(Color.red, lineWidth: borderWidth)
)
}
}
// Rounded corner with shadow demo code
struct RoundedCornerWithShadow: View {
var body: some View {
Text("Hello World")
.modifier(RoundedCornerWithShadowModifier(cornerRadius: 12.0, isShadow: true, borderColor: .red, borderWidth: 1.0))
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment