I am trying to replicate a component written in UIKit using SwiftUI
It is a 'shadowed card container' that looks like this -
You see the shadow effect has an offset and height value to it
Trying to create this in SwiftUI I cannot get it quite right -
The UIKit view is handled via an extension -
public extension UIView {
func addShadow(offset: CGSize = .init(width: 0, height: 3), color: UIColor = .init(red: 0, green: 0, blue: 0, alpha: 0.16), radius: CGFloat = 2, opacity: Float = 1) {
layer.masksToBounds = false
layer.shadowOffset = offset
layer.shadowColor = color.cgColor
layer.shadowRadius = radius
layer.shadowOpacity = opacity
layer.shouldRasterize = true
layer.rasterizationScale = UIScreen.main.scale
}
}
On a view -
public class CardContainerView: UIView {
private var didlLayoutSubviews = false
public override init(frame: CGRect) {
super.init(frame: frame)
configureUI()
}
required init?(coder: NSCoder) {
return nil
}
public override func layoutSubviews() {
super.layoutSubviews()
guard !didlLayoutSubviews else { return }
didlLayoutSubviews = true
addShadow(
offset: .init(width: 0, height: 3),
color: .init(red: 0, green: 0, blue: 0, alpha: 0.16),
radius: 2
)
}
}
private extension CardContainerView {
func configureUI() {
layer.cornerRadius = 12
clipsToBounds = true
}
}
I have tried this in SwiftUI and come up with -
public struct CardView<Content>: View where Content: View {
private var content: () -> Content
public init(@ViewBuilder _ content: @escaping () -> Content) {
self.content = content
}
public var body: some View {
VStack(content: content)
.padding()
.frame(maxWidth: .infinity, minHeight: 100, alignment: .top)
.background(Color(.tertiarySystemBackground))
.cornerRadius(12)
.shadow(
color: Color(.init(red: 0, green: 0, blue: 0, alpha: 0.16)),
radius: 2
)
}
}
I cannot understand how to apply the height and offset values to the shadow in SwiftUI
You can apply the offset values to the x
and y
values of the shadow.
VStack(content: content)
.padding()
.frame(maxWidth: .infinity, minHeight: 100, alignment: .top)
.background(Color(.tertiarySystemBackground))
.cornerRadius(12)
.shadow(
color: Color(.init(red: 0, green: 0, blue: 0, alpha: 0.16)),
radius: 2,
y: 3 // This should give you the same effect
)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.