我想為 a 創建一個初始化程式VStack,它將我的自定義列舉作為它的間距元素。我有這個代碼:
enum Styles {
enum Spacing: CGFloat {
case one = 4
case two = 8
case three = 16
}
}
extension VStack where Content: View {
init(
alignment: HorizontalAlignment = .center,
spacing: Styles.Spacing? = nil,
content: () -> Content
) {
self.init(
alignment: alignment,
spacing: spacing?.rawValue ?? Styles.Spacing.three.rawValue,
content: content
)
}
}
當我在@ViewBuilder函式中使用自定義 VStack 初始化程式時,它會回傳錯誤Type '()' cannot conform to 'View'。這是發生這種情況的示例:
@ViewBuilder
private func textBlock(
question: String,
answer: String
) -> some View {
VStack(
alignment: .leading,
spacing: .three
) {
Text(question)
Text(answer)
}
}
我怎樣才能解決這個問題?
uj5u.com熱心網友回復:
您需要將您的content引數標記為@ViewBuilder:
@ViewBuilder content: () -> Content
一些考慮:
- 您當前的實作
textBlock不需要標記為@ViewBuilder(除非您計劃在 之后添加更多視圖VStack),因此您可以將其洗掉。 - 可選
spacing引數根本不起作用,因為任何呼叫VStack(alignment: <something>)都會與您的簽名沖突(因為您為 提供了默認值spacing)并且編譯器將不知道應該使用哪個初始化程式。因此,您必須將其設為非可選。
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/407089.html
標籤:
