[英]How can I replicate this shadow + offset in SwiftUI
I am trying to replicate a component written in UIKit using SwiftUI我正在尝试使用 SwiftUI 复制用 UIKit 编写的组件
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 -试图在 SwiftUI 中创建它我无法完全正确 -
The UIKit view is handled via an extension - UIKit 视图通过扩展处理 -
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 -我已经在 SwiftUI 中尝试过这个并想出了 -
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我不明白如何将高度和偏移值应用于 SwiftUI 中的阴影
You can apply the offset values to the x
and y
values of the shadow.您可以将偏移值应用于阴影的x
和y
值。
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
)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.