SwiftUI-动画视图扩展(显示/隐藏) [英] SwiftUI - Animate View expansion (show / hide)
问题描述
我有一个 View
,其中包含一个 HStack
和一个 DatePicker
.当您点击 HStack
时, DatePicker
会显示/隐藏.我想对此动作进行动画处理,例如iOS日历的新事件视图"中开始和结束"行的动画.
I have a View
that contains a HStack
and a DatePicker
. When you tap on the HStack
, the DatePicker
is shown / hidden. I want to animate this action like the animation of Starts and Ends row in iOS Calendar's New Event View.
struct TimePicker: View {
@Binding var startTime: Date
@State private var isDatePickerVisible: Bool = false
var body: some View {
VStack(alignment: .center) {
HStack {
ListItemView(icon: "start-time",
leadingText: "Start Time",
trailingText: startTime.stringTime())
}
.onTapGesture {
withAnimation {
self.isDatePickerVisible.toggle()
}
}
Group {
if isDatePickerVisible {
DatePicker("", selection: $startTime, displayedComponents: [.hourAndMinute])
.datePickerStyle(WheelDatePickerStyle())
}
}
.background(Color.red)
.modifier(AnimatingCellHeight(height: isDatePickerVisible ? 300 : 0))
}
}
}
我已将以下代码用于动画.它几乎可以正常工作.唯一的问题是 HStack
跳转.而且我无法解决.
I have used the following code for animation. It almost works. The only problem is that HStack
jumps. And I can not fix it.
https://stackoverflow.com/a/60873883/8292178
struct AnimatingCellHeight: AnimatableModifier {
var height: CGFloat = 0
var animatableData: CGFloat {
get { height }
set { height = newValue }
}
func body(content: Content) -> some View {
content.frame(height: height)
}
}
如何解决此问题?如何为 DatePicker
的可见性设置动画?
How to fix this issue? How to animate visibility of the DatePicker
?
推荐答案
很简单,您不需要额外的 ViewModifier
It's simple, you don't need extra ViewModifier
struct TimePicker: View {
@Binding var startTime: Date
@State private var isDatePickerVisible: Bool = false
var body: some View {
VStack(alignment: .center) {
HStack {
ListItemView(icon: "start-time"
, leadingText: "Start Time"
, trailingText: startTime.stringTime())
}.onTapGesture {
isDatePickerVisible.toggle()
}
if isDatePickerVisible {
DatePicker(""
, selection: $model.startTime
, displayedComponents: [.hourAndMinute]
).datePickerStyle(WheelDatePickerStyle())
}
}.animation(.spring())
}
}
这篇关于SwiftUI-动画视图扩展(显示/隐藏)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!