繁体   English   中英

如何在 SwiftUI 中复制此阴影 + 偏移

[英]How can I replicate this shadow + offset in SwiftUI

我正在尝试使用 SwiftUI 复制用 UIKit 编写的组件

它是一个看起来像这样的“影子卡片容器”——

预期的

您会看到阴影效果有一个偏移量和高度值

试图在 SwiftUI 中创建它我无法完全正确 -

结果

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
    }
}

在一个视图 -


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
    }
}

我已经在 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
            )
    }
}

我不明白如何将高度和偏移值应用于 SwiftUI 中的阴影

您可以将偏移值应用于阴影的xy值。

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM