如何使用 SwiftUI 将视图拉伸到其父框架? [英] How do I stretch a View to its parent frame with SwiftUI?
本文介绍了如何使用 SwiftUI 将视图拉伸到其父框架?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在您下方,您可以看到图像和我想拉伸到红色边框的黑色方块.
Below you see the image and the black square i want to stretch to the red borders.
我已经尝试了以下
import SwiftUI
struct ContentView : View {
var body: some View {
HStack(spacing: 1) {
Rectangle().frame(width:20).foregroundColor(.red).frame(width:20)
ScrollView {
VStack {
ForEach(0..<5) { index in
Rectangle().frame(minWidth: 50, maxWidth: .infinity, minHeight: 50, maxHeight: 50)
}
}.relativeWidth(1)
}
Rectangle().foregroundColor(.red).frame(width:20)
}
}
}
#if DEBUG
struct ContentView_Previews : PreviewProvider {
static var previews: some View { ContentView() }
}
#endif
但结果是这样的:
推荐答案
您可以使用 GeometryReader 并将您的 ScrollView 包装到其中并将内容宽度设置为几何体的宽度大小.GeometryReader
:
You can use GeometryReader and wrap your ScrollView into it and set content width to the geometry's width size. A GeometryReader
:
返回一个灵活的首选大小给它的父布局.
returns a flexible preferred size to its parent layout.
因此您的代码将如下所示:
So your code would be something like below:
HStack(spacing: 1) {
Rectangle().frame(width:20).foregroundColor(.red).frame(width:20)
GeometryReader { geometry in
ScrollView {
VStack {
ForEach(0..<5) { index in
Rectangle().frame(minWidth: 50, maxWidth: .infinity, minHeight: 50, maxHeight: 50)
}
}.relativeWidth(1)
.frame(width: geometry.size.width)
}
}
Rectangle().foregroundColor(.red).frame(width:20)
}
这篇关于如何使用 SwiftUI 将视图拉伸到其父框架?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文