叠加视图不会在Stack-SwiftUI中自行维护



我在玩像这样的文本渐变动画

struct ContentView: View {
@State var lorem = "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum."
var body: some View {
VStack() {
Text(lorem)
.multilineTextAlignment(.center)
.foregroundColor(Color.blue)
.fontWeight(.bold)
}
.frame(maxHeight: .infinity)
.overlay(alignment: .topLeading) {
Button("Delete") {
withAnimation {
lorem = ""
}
}
}
.overlay(alignment: .topTrailing) {
Button("Reset") {
withAnimation {
lorem = "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum."
}
}

}
}
}

我的代码和一切看起来都很好,到目前为止没有任何错误,但每次我点击覆盖删除按钮时,一切都会逐渐消失。其他网站说Vstack的高度取决于我的文本的高度,所以所有的东西都崩溃了,所以我尝试将高度设置为";无穷大";然而仍然不起作用。

这是因为您使用的是.overlay{}

当您的Text()视图为空时,VStack()会自行收缩,并且也会变为空,因为其中没有元素,因此VStack的overlay{}也会消失。

您可以使用ZStack并将Color.clear用作其伪背景,或者使用.popacity来解决此问题。

试试这个修改后的代码:

var body: some View {
ZStack() { //modified
Color.clear.edgesIgnoringSafeArea(.all) //added
Text(lorem)
.multilineTextAlignment(.center)
.foregroundColor(Color.blue)
.fontWeight(.bold)
}
.overlay(alignment: .topLeading) {
Button("Delete") {
withAnimation {
lorem = ""
}
}
}
.overlay(alignment: .topTrailing) {
Button("Reset") {
withAnimation {
lorem = "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum."
}
}

}

最新更新