我为无法在 Sheet View 中实现 Flash 效果(将不透明度从 1 更改为 0 再更改回来)的问题准备了一些示例代码。此问题在屏幕上也可见。有人知道为什么会发生这种情况以及如何在 SwiftUI 中实现与 FlashButton 相同的效果吗?
import SwiftUI
struct ContentView: View {
@State var shouldFlashScreen = false
@State var openSheet = false
var body: some View {
VStack {
sheetButton
.frame(width: 100, height: 100)
flashButton
.frame(width: 100, height: 100)
}
}
@ViewBuilder
var sheetButton: some View {
Button {
openSheet = true
} label: {
Text("Open sheet")
}
.sheet(isPresented: $openSheet) {
flashButton
}
}
@ViewBuilder
var flashButton: some View {
ZStack {
Button {
shouldFlashScreen = true
withAnimation(.linear(duration: 0.05)) {
shouldFlashScreen = false
}
} label: {
Text("Tap to flash")
}
}
.frame(maxWidth: .infinity, maxHeight: .infinity)
.background(.gray)
.opacity(shouldFlashScreen ? 0 : 1)
.border(.red)
}
}
#Preview {
ContentView()
}
尝试改变应用不透明度变化的方式并使用
completion
动画的回调: