我正在创建一个 Swift 包,它将在指定的持续时间内闪烁一些文本(如 toast 实现。)我希望用户可以选择在对项目的调用中指定背景形状,但是当我只是尝试创建一个形状参数,我在声明行出现编译错误(错误 1):
协议“形状”只能用作通用约束,因为它具有自身或相关类型要求
以及我尝试使用它的地方(错误2):
作为一种类型的协议“形状”不能符合协议本身
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 的此类错误的帖子,但如果这确实是解决方案,我似乎无法弄清楚如何在这里实现它。
任何帮助表示赞赏。