问题描述
我正在尝试在Multiplatform实现中实现列表,这是我的实现:
struct ContentView: View {
var body: some View {
List {
Section(header: Text("Header"),footer: Text("Footer")){
ForEach(0..<5){
Text("\($0)")
.tag($0)
}
}
#if os(iOS)
.listStyle(GroupedListStyle())
#endif
}
}
}
但是在这一行:
.listStyle(GroupedListStyle())
我收到此错误:
Unexpected platform condition (expected `os`,`arch`,or `swift`)
非常感谢您的帮助
解决方法
SwiftUI不太喜欢条件编译代码。
尝试这样的事情:
#if os(macOS)
typealias MyListStyle = PlainListStyle
#else
typealias MyListStyle = GroupedListStyle
#endif
...
SomeView {}
.listStyle(MyListStyle())
或
func myListStyle() -> some View {
#if os(macOS)
return listStyle(PlainListStyle())
#else
return listStyle(GroupedListStyle())
#endif
}
...
SomeView {}
.myListStyle()
对于不合适的修饰符,您还可以使用func
的变体和返回的self
。我还用它来使.environment
有条件。