代碼:
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()
}
}
我收到此錯誤:
無法將“文本”型別的值轉換為閉包結果型別“內容”
我想要實作的目標是擁有 2 個單獨的初始化程式,一個用于 type 的內容,View另一個是字串的快捷方式,它將放置一個Text具有某種樣式的預定義組件來代替Content.
Text如果是,為什么我會收到此錯誤some View并且我認為它應該編譯。
uj5u.com熱心網友回復:
一種方法是使內容可選并使用另一個文本變數并基于 nil 值顯示視圖。
public struct Snackbar<Content>: View where Content: View {
private var content: Content? // <= Here
private var text: String = "" // <= Here
// Works OK
public init(@ViewBuilder content: () -> Content) {
self.content = content()
}
init(_ text: String) {
self.text = text // <= Here
}
public var body: some View {
HStack {
VStack(alignment: .leading, spacing: 4) {
if let content = content { // <= Here
content
} else {
Text(text)
.font(.subheadline)
.foregroundColor(.white)
.multilineTextAlignment(.leading)
}
}
Spacer()
}
// Other code
你也可以使用AnyView
public struct Snackbar: View {
private var content: AnyView // Here
// Works OK
public init<Content: View>(@ViewBuilder content: () -> Content) {
self.content = AnyView(content()) // Here
}
init(_ text: String) {
self.content = AnyView(Text(text)
.font(.subheadline)
.foregroundColor(.white)
.multilineTextAlignment(.leading)
) // Here
}
public var body: some View {
HStack {
VStack(alignment: .leading, spacing: 4) {
self.content
}
Spacer()
}
uj5u.com熱心網友回復:
您可以指定Content.
代碼:
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) where Content == ModifiedContent<Text, _EnvironmentKeyWritingModifier<TextAlignment>> {
self.init {
Text(text)
.font(.subheadline)
.foregroundColor(.white)
.multilineTextAlignment(.leading) as! ModifiedContent<Text, _EnvironmentKeyWritingModifier<TextAlignment>>
}
}
/* ... */
}
這里唯一的區別是 .where之后init和強制轉換為init.
為避免特定型別,您可以將其抽象為單獨的視圖:
init(_ text: String) where Content == ModifiedText {
self.init {
ModifiedText(text: text)
}
}
/* ... */
struct ModifiedText: View {
let text: String
var body: some View {
Text(text)
.font(.subheadline)
.foregroundColor(.white)
.multilineTextAlignment(.leading)
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/438917.html
