我在StackOverflow上发现了一些关于创建灵活布局(FlowLayout(的问题,比如标签通常会根据文本显示不同的按钮宽度,必要时会在多行上显示。
代码类似于:
@State var buttonStrings:[String]=[String]()
init()
{
self.buttonStrings=createStrings()
}
private func item(for text: String) -> some View {
Button(action:{doSomething()})
{
Text(text)
}
}
private func generateContent(in g: GeometryProxy) -> some View {
var width = CGFloat.zero
var height = CGFloat.zero
return ZStack(alignment: .topLeading) {
ForEach(self.buttonStrings, id: .self) { string in
self.item(for: string)
.padding([.horizontal, .vertical], 4)
.alignmentGuide(.leading, computeValue: { d in
if (abs(width - d.width) > g.size.width)
{
width = 0
height -= d.height
}
let result = width
if string == self.buttonStrings.last! {
width = 0 //last item
} else {
width -= d.width
}
return result
})
.alignmentGuide(.top, computeValue: {d in
let result = height
if string == self.buttonStrings.last! {
height = 0 // last item
}
return result
})
}
}
}
它是有效的,但当这种视图在VStack内部,另一个视图紧随其后时,它会垂直溢出到另一个图上(或者根据布局配置和Stacks的存在,它会将其驱逐到底部(。
如何才能避免这种情况,并使灵活的观点不泛滥或过于庞大?事实上,它内部的观点是移位的,这导致了这个问题。
使用该代码的正确方法是
struct FlowLayoutLikeView:View
{
var geometry:GeometryProxy
@State var buttonStrings:[String]=[String]()
init(geometry:GeometryProxy,....)
{
self.geometry=geometry
...
...
}
var body: some View {
self.generateContent(in: geometry)
}
private func item(for text: String) -> some View {
Button(action:{doSomething()})
{
Text(text)
}
}
private func generateContent(in g: GeometryProxy) -> some View {
var width = CGFloat.zero
var height = CGFloat.zero
return ZStack(alignment: .topLeading) {
ForEach(self.buttonStrings, id: .self) { string in
self.item(for: string)
.padding([.horizontal, .vertical], 4)
.alignmentGuide(.leading, computeValue: { d in
if (abs(width - d.width) > g.size.width)
{
width = 0
height -= d.height
}
let result = width
if string == self.buttonStrings.last! {
width = 0 //last item
} else {
width -= d.width
}
return result
})
.alignmentGuide(.top, computeValue: {d in
let result = height
if string == self.buttonStrings.last! {
height = 0 // last item
}
return result
})
}
}
}
包含的视图必须像一样
var body: some View {
VStack //this does the trick, do not remove
{
GeometryReader { geometry in
VStack //this also does the trick, do not remove
{
FlowLayoutLikeView(geometry)
AnotherView() //this will be fine, it will be placed below the FlowLayoutLikeView, no overlapping, overflowing or ousting
}
}
}
}