[英]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 中的陰影
您可以將偏移值應用於陰影的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.