SwiftUI在准备底页时偏移动画问题
Posted
技术标签:
【中文标题】SwiftUI在准备底页时偏移动画问题【英文标题】:SwiftUI offset animation problem while in preparing bottomsheet 【发布时间】:2021-08-08 19:07:35 【问题描述】:我想自己努力在SwiftUI中做一个bottomsheet,我用动画打开它,但是我的动画在关闭时不起作用,是什么原因? 我想知道偏移值是否随着动画的增加而增加,减少时是否有问题我不太擅长 SwiftUI,所以我无法完全理解这个问题。
struct ContentView: View
@State var isOpen = false
@State var offset = UIScreen.main.bounds.height / 3
var body: some View
ZStack
Color.blue
.ignoresSafeArea()
Button(action:
self.isOpen.toggle()
, label:
ZStack
RoundedRectangle(cornerRadius: 25.0)
.foregroundColor(.black)
Text("Open")
.font(.title2)
.fontWeight(.bold)
.foregroundColor(.white)
)
.buttonStyle(DefaultButtonStyle())
.frame(width: 300, height: 50, alignment: .center)
if isOpen
GeometryReader geometry in
VStack
Spacer()
BottomSheet()
.frame(width: geometry.size.width,
height: geometry.size.height / 3,
alignment: .center)
.background(
Color.white
)
.offset(y: offset)
.onAppear(perform:
withAnimation
self.offset = 0
)
.onDisappear(perform:
withAnimation
self.offset = UIScreen.main.bounds.height / 3
)
.ignoresSafeArea()
底页
struct BottomSheet: View
var body: some View
Text("Hello, World!")
【问题讨论】:
【参考方案1】:onDisappear
在视图被移除时被调用,这就是自定义动画不起作用的原因:
struct ContentView: View
@State var isOpen = false
var offset: CGFloat
isOpen ? 0 : UIScreen.main.bounds.height / 3
var body: some View
ZStack
Color.blue
.ignoresSafeArea()
Button(action:
self.isOpen.toggle()
, label:
ZStack
RoundedRectangle(cornerRadius: 25.0)
.foregroundColor(.black)
Text("Open")
.font(.title2)
.fontWeight(.bold)
.foregroundColor(.white)
)
.buttonStyle(DefaultButtonStyle())
.frame(width: 300, height: 50, alignment: .center)
GeometryReader geometry in
VStack
Spacer()
BottomSheet()
.frame(width:geometry.size.width,
height: geometry.size.height / 3,
alignment: .center)
.background(
Color.white
)
.offset(y: offset)
.animation(.easeInOut(duration: 0.5)) .transition(.move(edge: .bottom))
.edgesIgnoringSafeArea(.bottom)
【讨论】:
以上是关于SwiftUI在准备底页时偏移动画问题的主要内容,如果未能解决你的问题,请参考以下文章
使用jetpack导航组件从一个底页导航到另一个底页时如何弹出底页对话框