A SwiftUI code to demonstrate how to create a shadow view in SwiftUI
This file contains 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 | |
struct ShadowComponent: View { | |
enum Direction { | |
case upward | |
case downward | |
func getStartEndPoints() -> (start: UnitPoint, end: UnitPoint) { | |
switch self { | |
case .upward: | |
return (.bottom, .top) | |
case .downward: | |
return (.top, .bottom) | |
} | |
} | |
} | |
let direction: Direction | |
var body: some View { | |
let startEndPoints = direction.getStartEndPoints() | |
LinearGradient(colors: [ | |
Color.gray.opacity(0.5), | |
Color.white.opacity(0.5) | |
], startPoint: startEndPoints.start, endPoint: startEndPoints.end).frame(height: 12) | |
} | |
} | |
struct ShadowContainerView<Content: View>: View { | |
let content: Content | |
let shadowPosition: ShadowPosition | |
enum ShadowPosition { | |
case top | |
case bottom | |
case all | |
} | |
init(content: @escaping () -> Content, | |
shadowPosition: ShadowPosition | |
) { | |
self.content = content() | |
self.shadowPosition = shadowPosition | |
} | |
var body: some View { | |
VStack { | |
if shadowPosition != .bottom { | |
ShadowComponent(direction: .upward) | |
} | |
content | |
if shadowPosition != .top { | |
ShadowComponent(direction: .downward) | |
} | |
} | |
} | |
} | |
struct ShadowComponent_Previews: PreviewProvider { | |
static var previews: some View { | |
VStack(spacing: 16) { | |
ShadowContainerView(content: { | |
VStack { | |
Text("Section 1") | |
Text("Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam").padding() | |
} | |
}, shadowPosition: .all) | |
ShadowContainerView(content: { | |
VStack { | |
Text("Section 2") | |
Text("Lorem ipsum dolor sit amet, coddectetur adidsding elit").padding() | |
} | |
}, shadowPosition: .all) | |
ShadowContainerView(content: { | |
VStack { | |
Text("Section 3") | |
Text("Lorem ipsumt. llamco laboris nisi ut aliquip ex ea commodo c").padding() | |
} | |
}, shadowPosition: .all) | |
ShadowContainerView(content: { | |
VStack { | |
Text("Section 4") | |
Text("Lorem ipsumt. llamco laboris nisi ut aliquip ex ea commodo c").padding() | |
} | |
}, shadowPosition: .all) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment