【发布时间】:2020-12-31 04:15:15
【问题描述】:
我正在使用 SwiftUI 开发跨平台应用程序。我有一个由HStack 组成的视图,其中排列着各种项目。本质上是这样的:
struct ContentView: View {
var body: some View {
HStack {
// Some stuff on the left side of this HStack
Spacer()
// more stuff on the right side
}
}
}
Spacer 尽可能多地占用空间,这会将它之前的视图推到左侧,并将它之后的视图推到行的右侧。我已经达到了在 iOS 上看起来很棒的地步。
不过,在 macOS 上,我的窗口宽度要大得多,并且可以由用户进一步调整大小。在那些较大的宽度上,看到行内容被如此多的空间分隔开来会变得很尴尬。所以我想限制宽度。本质上,我想这样做:
struct ContentView: View {
var body: some View {
HStack {
// a bunch of stuff in this stack
}
#if os(macOS)
.frame(width: 120)
#endif
}
}
但这让我收到来自带有.frame 修饰符的行的错误“意外的平台条件(预期的'os'、'arch'或'swift')”。如果我在平台检查中重新创建整个HStack,如下所示,一切正常。
struct ContentView: View {
var body: some View {
#if os(iOS)
HStack {
// a bunch of stuff in this stack
}
#elseif os(macOS)
HStack {
// a bunch of stuff in this stack
}
.frame(width: 120)
#endif
}
}
但是复制HStack 中的所有内容似乎很容易出错,只是为了能够根据平台改变修饰符。真的没有办法有条件地编译just修饰符代码吗?
【问题讨论】: