How make animations work inside ScrollView in SwiftUI? Accordion style animation in SwiftUI - ios

I am trying to build a accordion style view with animations using SwiftUI. But Animations are not working properly if I wrap it into a ScrollView.Below is the code that I am trying to work out.
struct ParentView: View {
#State var isPressed = false
var body: some View {
GeometryReader { geometry in
ScrollView {
Group {
SampleView(index: 1)
SampleView(index: 2)
SampleView(index: 3)
SampleView(index: 4)
}.border(Color.black).frame(maxWidth: .infinity)
}.border(Color.green)
}
}
}
struct SampleView: View {
#State var index: Int
#State var isPressed = false
var body: some View {
Group {
HStack(alignment:.top) {
VStack(alignment: .leading) {
Text("********************")
Text("This View = \(index)")
Text("********************")
}
Spacer()
Button("Press") { self.isPressed.toggle() }
}
if isPressed {
VStack(alignment: .leading) {
Text("********************")
Text("-----> = \(index)")
Text("********************")
}.transition(.slide).animation(.linear).border(Color.red)
}
}
}
}
And Below is the screenshot of problem I'm facing.

To make it animate, wrap self.isPressed.toggle() in a withAnimation closure.
Button("Press") { withAnimation { self.isPressed.toggle() } }

Related

Why does withAnimation not cause an animation?

I try to switch from one screen to another by pressing a button (see full code below). The switch from the first view to the second view (and vice versa) works, but no animation is taking place.
Why does this behavior happen?
Full code:
struct ContentView: View {
#AppStorage("firstViewActive") var isFirstViewActive: Bool = true
var body: some View {
if isFirstViewActive {
FirstView()
} else {
SecondView()
}
}
}
struct FirstView: View {
#AppStorage("firstViewActive") var isFirstViewActive: Bool = true
var body: some View {
ZStack {
Color(.red).ignoresSafeArea(.all, edges: .all)
VStack {
Spacer()
Text("This is the first view")
Spacer()
Button {
withAnimation {
isFirstViewActive = false
}
} label: {
Text("Go to second view")
}
Spacer()
}
}
}
}
struct SecondView: View {
#AppStorage("firstViewActive") var isFirstViewActive: Bool = false
var body: some View {
ZStack {
Color(.blue).ignoresSafeArea(.all, edges: .all)
VStack {
Spacer()
Text("This is the second view")
Spacer()
Button {
withAnimation {
isFirstViewActive = true
}
} label: {
Text("Go to first view")
}
Spacer()
}
}
}
}
The problem is with
#AppStorage("firstViewActive") var isFirstViewActive: Bool = true
If you change that to
#State var isFirstViewActive: Bool = true
and use #Binding in subviews, you will get the default animations.
In iOS 16, there seems to be a problem with #AppStorage vars and animation. But you can refer to this workaround

Conditional component in SwiftUI

I'm giving my first steps with SwiftUI and I'm having problems with a component shown depending on a condition.
I'm trying to show a fullscreen popup (full screen with semi transparent black background and the popup in the middle with white background). To achieve this I've made this component:
struct CustomUiPopup: View {
var body: some View {
ZStack {
}
.overlay(CustomUiPopupOverlay, alignment: .top)
.zIndex(1)
}
private var CustomUiPopupOverlay: some View {
ZStack {
Spacer()
ZStack {
Text("POPUP")
.padding()
}
.zIndex(1)
.frame(width: UIScreen.main.bounds.size.width - 66)
.background(Color.white)
.cornerRadius(8)
Spacer()
}
.frame(width: UIScreen.main.bounds.size.width, height: UIScreen.main.bounds.size.height)
.background(Color.black.opacity(0.6))
}
}
If I set this in my main view, the popup is shown correctly over the button:
struct MainView: View {
var body: some View {
CustomUiPopup()
Button("Click to show popup") {
print("click on button")
}
}
}
If I set this, my popup is not shown (correct because hasToShowPopup is false), but if I click on the button it fails, the popup is not shown and the button can not be clicked again (?!), it seems like the view was freezed.
struct MainView: View {
#State private var hasToShowPopup = false
var body: some View {
if hasToShowPopup {
CustomUiPopup()
}
Button("Click to show popup") {
hasToShowPopup = true
}
}
}
I've even tried to initializate hasToShowPopup to true but the popup keeps failing, it's not shown in the first place:
struct MainView: View {
#State private var hasToShowPopup = true
var body: some View {
if hasToShowPopup {
CustomUiPopup()
}
Button("Click to show popup") {
hasToShowPopup = true
}
}
}
So my conclusion is that, I don't know why, but if I put my CustomUiPopup inside an "if" something is not rendered correctly.
What is wrong with my code?
Anyway, if this is not the correct approach to show a popup, I'll be glad to have any advice.
Following Ptit Xav suggestion I've tried this with the same results (my CustomUiPopup doesn't show):
struct MainView: View {
#State private var hasToShowPopup = false
var body: some View {
VStack {
if hasToShowPopup {
CustomUiPopup()
}
Button("Click to show popup") {
hasToShowPopup = true
}
}
}
}
This works fine with me:
struct CustomUiPopup: View {
var body: some View {
ZStack {
Spacer()
Text("POPUP")
.padding()
.zIndex(1)
.frame(width: UIScreen.main.bounds.size.width - 66)
.background(Color.white)
.cornerRadius(8)
Spacer()
}
.frame(maxWidth: .infinity, maxHeight: .infinity)
.background(
Color.black.opacity(0.6)
.ignoresSafeArea()
)
}
}
struct ContentView: View {
#State private var hasToShowPopup = false
var body: some View {
ZStack {
Button("Click to show popup") {
hasToShowPopup = true
}
if hasToShowPopup {
CustomUiPopup()
}
}
}
}

Scroll to correct position in SwiftUI when a list item is clicked

I've a SwiftUI ForEach loop which contains views that expand when clicked. Something similar to the view shown below.
struct ExpandingView: View {
#State var isExpanded = false
var body: some View {
VStack {
Text("Hello!")
if isExpanded {
Text("World")
}
}
.onTapGesture {
withAnimation {
isExpanded.toggle()
}
}
}
}
In theory, I can use the ScrollViewReader and scrollTo a particular position.
ScrollViewReader { view in
ScrollView {
ForEach(0...100, id: \.self) { id in
ExpandingView()
.id(id)
.padding()
}
}
}
However, in practice, I'm not sure how to get the id from within the view (because onTapGesture is in the view) and propagate it up one level.
The other option is to have the onTapGesture in the ForEach loop, but then I'm not sure how to toggle the isExpanded flag for the correct view.
You can pass a ScrollViewProxy to row view and then you can now able to scroll.
struct ExpandingView: View {
#State var isExpanded = false
var id: Int
var proxy: ScrollViewProxy
var body: some View {
VStack {
Text("Hello!")
if isExpanded {
Text("World")
}
}
.onTapGesture {
withAnimation {
isExpanded.toggle()
proxy.scrollTo(id, anchor: .center)
}
}
}
}
struct TestScrollView: View {
var body: some View {
ScrollViewReader { view in
ScrollView {
ForEach(0...100, id: \.self) { id in
ExpandingView(id: id, proxy: view)
.id(id)
.padding()
}
}
}
}
}
if I understand your question correctly, you are asking how to pass the id in "ContentView ScrollView"
into ExpandingView. Try this:
import SwiftUI
#main
struct TestApp: App {
var body: some Scene {
WindowGroup {
ContentView()
}
}
}
struct ExpandingView: View {
#State var worldId: Int
#State var isExpanded = false
var body: some View {
VStack {
Text("Hello!")
if isExpanded { Text("World \(worldId)") }
}.onTapGesture {
withAnimation { isExpanded.toggle() }
}
}
}
struct ContentView: View {
var body: some View {
ScrollViewReader { view in
ScrollView {
ForEach(0...100, id: \.self) { id in
ExpandingView(worldId: id).id(id).padding()
}
}
}
}
}

Can I use a button inside a SwiftUI sheet view that appears on top of my main SwiftUI view to change a subview inside the main view?

I'm trying to use a pop up menu (that appears when the user triggers it) to make the users of my app able to change the subview that is shown inside my main view between a Subview1 and a Subview2.
I'm trying to do that using global Bool variables that are changed when a button in the view inside the sheet is pressed. Based on those values, the main view should return a different subview
The problem is that when I try to select one option from the view that appears inside the sheet, the action of the Button is performed and the sheet is dismissed but the subview displayed by the main view remains unchanged
Is there a way to change the subview or reload the main view?
The code I'm using for the main view is:
struct ContentView: View {
#State var showMenu = false
var body: some View {
if(subview1Selected){
return AnyView(SubView1())
} else if (subview2Selected){
return AnyView(SubView2())
}
else {
return AnyView(
Button(action: {
showMenu = true
})
{
Text("Button")
}
.sheet(isPresented: $showMenu, content: {
MenuView()
})
)
}
}
the code I'm using for the pop-up sheet that is used like a menu is:
struct MenuView: View {
#Environment(\.presentationMode) var presentationMode
var body: some View {
List{
Button(action: {
subview1Selected = true
subview2Selected = false
self.presentationMode.wrappedValue.dismiss()
})
{
Text("Subview1")
}
Button(action: {
subview2Selected = true
subview1Selected = false
self.presentationMode.wrappedValue.dismiss()
})
{
Text("Subview2")
}
}
}
}
The subviews are:
struct SubView1: View {
#State var showMenu = false
var body: some View {
Button(action: {
showMenu = true
})
{
Text("SubView1")
}
.sheet(isPresented: $showMenu, content: {
MenuView()
})
}
}
and:
struct SubView2: View {
#State var showMenu = false
var body: some View {
Button(action: {
showMenu = true
})
{
Text("SubView2")
}
.sheet(isPresented: $showMenu, content: {
MenuView()
})
}
}
I think this is what you are trying to do. You can pass the #State showMenu variable as a #Binding variable into the menu. You can use a Bool if you only have 2 views, but it's more practical to use a custom enum, which I added for you. Also, the menu button should probably be separate from the subviews.
struct ContentView: View {
enum SubViewOption {
case subview1
case subview2
}
#State var showMenu = false
#State var subviewSelected: SubViewOption?
var body: some View {
ZStack() {
switch subviewSelected {
case .subview1:
SubView1()
case .subview2:
SubView2()
default:
Text("Select a view to begin.")
}
}
.frame(maxWidth: .infinity, maxHeight: .infinity)
.overlay(
Button(action: {
showMenu.toggle()
}, label: {
Text("Menu")
.padding()
.frame(maxWidth: .infinity)
.foregroundColor(.white)
.background(Color.gray.cornerRadius(30))
.padding()
})
, alignment: .bottom
)
.sheet(isPresented: $showMenu, content: {
MenuView(subviewSelected: $subviewSelected)
})
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
struct MenuView: View {
#Environment(\.presentationMode) var presentationMode
#Binding var subviewSelected: ContentView.SubViewOption?
var body: some View {
List {
Button(action: {
subviewSelected = .subview1
presentationMode.wrappedValue.dismiss()
}, label: {
Text("Subview1")
})
Button(action: {
subviewSelected = .subview2
presentationMode.wrappedValue.dismiss()
}, label: {
Text("Subview2")
})
}
}
}
struct SubView1: View {
var body: some View {
ZStack {
Color.red
.edgesIgnoringSafeArea(.all)
Text("THIS IS SUBVIEW 1")
.foregroundColor(.white)
}
}
}
struct SubView2: View {
var body: some View {
ZStack {
Color.blue
.edgesIgnoringSafeArea(.all)
Text("THIS IS SUBVIEW 2")
.foregroundColor(.white)
}
}
}

SwiftUI - Animate View expansion (show / hide)

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))
}
}
}
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)
}
}
How to fix this issue? How to animate visibility of the DatePicker?
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())
}
}

Resources