代码:
import SwiftUI
public struct Snackbar<Content>: View where Content: View {
private var content: Content
// Works OK
public init(@ViewBuilder content: () -> Content) {
self.content = content()
}
init(_ text: String) {
self.init {
Text(text) // cannot convert value of type 'Text' to closure result type 'Content'
.font(.subheadline)
.foregroundColor(.white)
.multilineTextAlignment(.leading)
}
}
public var body: some View {
HStack {
VStack(alignment: .leading, spacing: 4) {
content
}
Spacer()
}
.frame(maxWidth: .infinity,
minHeight: 26)
.padding(.fullPadding)
.background(Color.black)
.clipShape(RoundedRectangle(cornerRadius: .defaultCornerRadius))
.shadow(color: Color.black.opacity(0.125), radius: 4, y: 4)
.padding()
}
}
我收到这个错误:
cannot convert value of type 'Text' to closure result type 'Content'
我试图实现的目标是拥有 2 个单独的初始化程序,一个用于 View
类型的内容,另一个是字符串的快捷方式,它将放置一个预定义的 Text
组件,用一些样式代替 Content
。
如果 Text
是 some View
并且我认为它应该编译,为什么我会收到此错误。
最佳答案
对此的通用解决方案是提供一个在语义上等同于 some View
的包装器。 AnyView
是内置的,可用于此目的。
init(_ text: String) where Content == AnyView {
self.init {
AnyView(
Text(text)
.font(.subheadline)
.foregroundColor(.white)
.multilineTextAlignment(.leading)
)
}
}
此外,将您的代码更改为
private let content: () -> Content
public init(@ViewBuilder content: @escaping () -> Content) {
self.content = content
}
这样您就不必将 content
的结果包装在另一个闭包中。
VStack(alignment: .leading, spacing: 4, content: content)
关于ios - SwiftUI View : two different initializers: cannot convert value of type 'Text' to closure result type 'Content' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71382967/