Fer*_*ios 5 swift swift-package-manager swift5
我正在创建一个 Swift 包,它将在指定的时间内闪烁一些文本(如 toast 实现)。我希望用户可以选择在调用该项目时指定背景形状,但是当我尝试创建一个Shape 参数,我在声明行收到编译错误(错误 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
}
}
}
Run Code Online (Sandbox Code Playgroud)
我见过其他使用 @ViewBuilders 出现此类错误的帖子,但我似乎无法弄清楚如何在此处实现它(如果这确实是解决方案)。
任何帮助表示赞赏。
以下是使其正常工作所需的更改:
对于类声明:
public struct Toast<Content: Shape>: View { ... }
Run Code Online (Sandbox Code Playgroud)
对于财产申报:
var shape: Content
Run Code Online (Sandbox Code Playgroud)
对于初始化声明:
shape: Content
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1028 次 |
| 最近记录: |