【问题标题】:Animation of Popup Screen Not Working SwiftUI弹出屏幕的动画不起作用 SwiftUI
【发布时间】:2022-01-19 20:13:31
【问题描述】:

我试图在按下按钮时弹出一个屏幕,然后在按下按钮或弹出屏幕上的“X”时消失。

下面的代码工作正常,除了我想要动画并且动画不起作用,弹出窗口只是出现和消失。这是怎么回事?

import SwiftUI

struct PopUpViewToggle: View {
    
    @State var show: Bool = false
    @State var offset: CGFloat = UIScreen.main.bounds.height
    
    var body: some View {
        ZStack {
            Button("Button") {
                show.toggle()
                offset = show ? UIScreen.main.bounds.height / 2 : UIScreen.main.bounds.height
            }
            if show {
                ScreenToggle(show: $show, offset: $offset)
                    .offset(y: offset)
                    .animation(.spring(), value: offset)
            }
        }
    }
}

struct ScreenToggle: View {
    
    @Binding var show: Bool
    @Binding var offset: CGFloat
    
    var body: some View {
        ZStack {
            RoundedRectangle(cornerRadius: 20)
                
            VStack {
                HStack {
                    Button {
                        show.toggle()
                        offset = show ? UIScreen.main.bounds.height / 2 : UIScreen.main.bounds.height
                    } label: { Image(systemName: "x.circle.fill").font(.largeTitle) }

                    Spacer()
                }
                .padding()
                Spacer()
            }
        }
    }
}

【问题讨论】:

    标签: swift animation swiftui popup


    【解决方案1】:

    show.toggle() 放入 withAnimation 块中。

    Button("Button") {
      offset = show ? UIScreen.main.bounds.height / 2 : UIScreen.main.bounds.height
      withAnimation {
        show.toggle()
      }
    }
    
    

    【讨论】:

      猜你喜欢
      • 2020-06-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-03-16
      • 1970-01-01
      • 2022-10-19
      相关资源
      最近更新 更多