当我点击Toggle Text
时,它必须使用淡入淡出和延迟隐藏或显示收藏夹 Text
。或在文本要在屏幕上显示时给我一些动画。 我尝试了几种动画方法,但到目前为止还无法正常工作。这是代码。
struct ContentView: View {
@State var showText: Bool
var body: some View {
VStack() {
Spacer()
Image(systemName: "star.fill")
if self.showText {
// Changing selection value.
Text("Favorites")
.font(.custom("Helvetica Neue", size: 20))
.animation(Animation.easeOut(duration: 2.0).delay(0.5))
}
Spacer()
.frame(height: 50)
Button(action: {
self.showText.toggle()
}) {
Text("Toggle Text")
}
Spacer()
}
.padding(5)
.font(.custom("Helvetica Neue", size: 14))
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView(showText: false)
}
}
这里是可能的方法(经过测试,可与Xcode 11.2 / iOS 13.2一起使用)
注意:预览在处理过渡时效果不好,因此请使用模拟器或真实设备进行测试。
struct ContentView: View {
@State var showText: Bool = false
var body: some View {
VStack() {
Spacer()
Image(systemName: "star.fill")
if self.showText {
// Changing selection value.
Text("Favorites")
.font(.custom("Helvetica Neue", size: 20))
.transition(.opacity) // << transition works in add/remove view
}
Spacer()
.frame(height: 50)
Button(action: {
withAnimation(Animation.easeOut(duration: 2.0).delay(0.5)) {
self.showText.toggle() // << transition requires explicit animation
}
}) {
Text("Toggle Text")
}
Spacer()
}
.padding(5)
.font(.custom("Helvetica Neue", size: 14))
}
}