這段代碼...
Text("Hello, world!")
.background(.regularMaterial, in: condition ? RoundedRectangle(cornerRadius: 6) : Circle())
...導致這個問題:
'? 中的結果值 :' 運算式具有不匹配的型別 'RoundedRectangle' 和 'Circle'
有沒有辦法在不使用if/else語法的情況下解決它?
uj5u.com熱心網友回復:
您可以嘗試使用以下方法使用extension Viewfrom
https://matteo-pucinelli.medium.com/conditionally-apply-modifiers-in-swiftui-51c1cf7f61d1
extension View {
@ViewBuilder
func ifCondition<TrueContent: View, FalseContent: View>(_ condition: Bool, then trueContent: (Self) -> TrueContent, else falseContent: (Self) -> FalseContent) -> some View {
if condition {
trueContent(self)
} else {
falseContent(self)
}
}
}
struct ContentView: View {
@State var condition = false
var body: some View {
Text("Hello, world").padding(20)
.ifCondition(condition) { text in
text.background(.regularMaterial, in: RoundedRectangle(cornerRadius: 6))
} else: { text in
text.background(.regularMaterial, in: Circle())
}
}
}
uj5u.com熱心網友回復:
或者,如果您想絕對堅持使用三元:
Text("Hello, world!")
.padding()
.background(
ZStack {
RoundedRectangle(cornerRadius: 6)
.fill(.regularMaterial)
.opacity(condition ? 1 :0)
Circle()
.fill(.regularMaterial)
.opacity(condition ? 0 :1)
}
)
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/431355.html
上一篇:在SwifUI中使用.fetchBatchSize和@FetchRequest
下一篇:旋轉到最接近的值標簽
