如何将 SwiftUI Shape 作为参数传递

How to pass a SwiftUI Shape as argument

我正在创建一个 Swift 程序包,它将在指定的持续时间内闪烁一些文本(如吐司实现)。我希望用户可以选择在调用该项目时指定背景形状,但是当我只是尝试创建一个 Shape 参数时,我在声明行(错误 1)上遇到编译错误:

协议'Shape'只能用作泛型约束,因为它有Self或关联类型要求

以及我尝试使用它的地方(错误 2):

协议'Shape'作为一种类型不能符合协议本身

import SwiftUI

public struct Toast: View {
    
    @Binding var show: Bool

    var message: String = ""
    var duration: Double = 2.0
    var fontSize: Font = .title
    var textColor: Color = Color(.secondaryLabel)
    var backgroundColor : Color = Color (.clear)
    var encapsulate: Bool = false
    var shape: Shape = Capsule() //Error 1
    
    public init(show: Binding<Bool>,
                message: String,
                duration: Double = 2.0,
                fontSize: Font = .title,
                textColor: Color = Color(.secondaryLabel),
                backgroundColor: Color = Color (.clear),
                encapsulate: Bool = false,
                shape: Shape = Capsule()) { //same as error 1
        
        self._show = show
        self.message = message
        self.duration = duration
        self.fontSize = fontSize
        self.textColor = textColor
        self.backgroundColor = backgroundColor
        self.encapsulate = encapsulate
        self.shape = shape
    }
    
    
    public var body: some View {
        Text(message)
            .font(fontSize)
            .foregroundColor(textColor)
            .padding(.horizontal)
            .padding(.vertical, 2.0)
            .background(backgroundColor)
            .if(encapsulate, transform: { view in
                view.clipShape(shape) //error 2
            })
            .onAppear(){
                DispatchQueue.main.asyncAfter(deadline: .now() + duration) {
                    show = false
                }
            }
    }

}

public extension View {
    /// Applies the given transform if the given condition evaluates to `true`.
    /// - Parameters:
    ///   - condition: The condition to evaluate.
    ///   - transform: The transform to apply to the source `View`.
    /// - Returns: Either the original `View` or the modified `View` if the condition is `true`.
    @ViewBuilder func `if`<Content: View>(_ condition: Bool, transform: (Self) -> Content) -> some View {
        if condition {
            transform(self)
        } else {
            self
        }
    }
}

我看到其他使用@ViewBuilders 出现此类错误的帖子,但如果这确实是解决方案,我似乎无法弄清楚如何在此处实现它。

感谢任何帮助。

以下是使其工作所需的更改:

对于 class 声明:

public struct Toast<Content: Shape>: View { ... }

对于属性声明:

var shape: Content 

初始化声明:

shape: Content