以相对宽度叠加
Overlay with relative Width
Xcode 11 Beta 4 弃用 .relativeSize
以及 .relativeWidth
和 .relativeHeight
(参见 )。
那么替代方案是什么?
我想创建一个相对于其父级具有宽度的叠加层。
假设我有以下主视图
struct MainView: View {
var body: some View {
ZStack(alignment: .topLeading) {
BackgroundView()
SideBarView()
.frame(idealWidth: 200)
.fixedSize(horizontal: true, vertical: false)
}
}
}
使用简单的 BackgroundView
和 SideBarView
以及那些按预期工作。
struct SideBarView: View {
var body: some View {
Rectangle()
.foregroundColor(.green)
}
}
struct BackgroundView: View {
var body: some View {
Rectangle()
.foregroundColor(.red)
}
}
这是在发行说明和 中建议的。
如何使用 .relativeWidth(0.3)
而不是 .frame(idealWidth:)
来避免像以前那样对这些值进行硬编码?1
1注意:使用 .relativeWidth
从未真正起作用,例如使用 0.3
作为相对值永远不会产生占父级宽度 30% 的视图,但您可以通过反复试验接近您想要的结果。
有多种方法可以实现,一种方法是使用 .overlay
而不是 ZStack
。您在叠加层中使用的视图将获得父级提供的 BackgroundView
的大小。然后你只需使用 GeometryReader 获得宽度并将其乘以 0.7:
struct ContentView: View {
var body: some View {
BackgroundView().overlay(SideBarView())
}
}
struct SideBarView: View {
var body: some View {
GeometryReader { proxy in
HStack {
Spacer()
Rectangle()
.frame(width: proxy.size.width * 0.7)
.fixedSize(horizontal: true, vertical: false)
.foregroundColor(.green)
}
}
}
}
struct BackgroundView: View {
var body: some View {
Rectangle()
.foregroundColor(.red)
}
}
Xcode 11 Beta 4 弃用 .relativeSize
以及 .relativeWidth
和 .relativeHeight
(参见
那么替代方案是什么?
我想创建一个相对于其父级具有宽度的叠加层。
假设我有以下主视图
struct MainView: View {
var body: some View {
ZStack(alignment: .topLeading) {
BackgroundView()
SideBarView()
.frame(idealWidth: 200)
.fixedSize(horizontal: true, vertical: false)
}
}
}
使用简单的 BackgroundView
和 SideBarView
以及那些按预期工作。
struct SideBarView: View {
var body: some View {
Rectangle()
.foregroundColor(.green)
}
}
struct BackgroundView: View {
var body: some View {
Rectangle()
.foregroundColor(.red)
}
}
这是在发行说明和
如何使用 .relativeWidth(0.3)
而不是 .frame(idealWidth:)
来避免像以前那样对这些值进行硬编码?1
1注意:使用 .relativeWidth
从未真正起作用,例如使用 0.3
作为相对值永远不会产生占父级宽度 30% 的视图,但您可以通过反复试验接近您想要的结果。
有多种方法可以实现,一种方法是使用 .overlay
而不是 ZStack
。您在叠加层中使用的视图将获得父级提供的 BackgroundView
的大小。然后你只需使用 GeometryReader 获得宽度并将其乘以 0.7:
struct ContentView: View {
var body: some View {
BackgroundView().overlay(SideBarView())
}
}
struct SideBarView: View {
var body: some View {
GeometryReader { proxy in
HStack {
Spacer()
Rectangle()
.frame(width: proxy.size.width * 0.7)
.fixedSize(horizontal: true, vertical: false)
.foregroundColor(.green)
}
}
}
}
struct BackgroundView: View {
var body: some View {
Rectangle()
.foregroundColor(.red)
}
}