I have a LazyVGrid that is defined like this:
let column = Array(repeating: GridItem(.flexible(minimum: 120, maximum: .infinity)), count: 3)
LazyVGrid(columns: column, alignment: .leading, spacing: 5) {
ForEach(data, id: \.self.uniqueStableId) { _ in
Color.red
.transition(.move(edge: .trailing))
.frame(height: 150)
}
}
I have a button, that starts an animation effect:
func handleButtonTap() {
for index in 0..<9 {
DispatchQueue.main.asyncAfter(deadline: .now() + Double(1 * index)) {
withAnimation(.easeInOut(duration: 1)) {
let newItem = Item()
self.data.append(newItem)
}
}
}
}
The animation should add the new Red squares into the grid one by one with 1 second intervals using a slide effect, but there are 2 issues:
even though I set a specific transition for the Red color view, the transition is ignored and the squares are added with a fade in effect
each time the first square in the row, is added in a new row on the grid, it appears from the middle of the row, and starts to slide vertically, the next squares in same row fade in
It appears I'm setting the transition and animation in the wrong place, because even if remove the .transition from the Red view, it still animates it the same way. Can't understand what controls it
Anyone has a hint how to adjust it to work properly?
Thanks!
I can reproduce your issue, and I don't know why it happens.
But I found a possible solution. If you wrap the LazyVGrid in s ScrollView it works:
struct Item: Identifiable {
let id = UUID()
}
struct ContentView: View {
#State private var data: [Item] = []
let column = Array(repeating: GridItem(.flexible()), count: 3)
var body: some View {
VStack {
Button("Add") { handleButtonTap() }
ScrollView {
LazyVGrid(columns: column, alignment: .leading, spacing: 5) {
ForEach(data) { _ in
Color.red
.frame(height: 150)
.transition(.move(edge: .trailing))
}
}
Spacer()
}
}
}
func handleButtonTap() {
for index in 0..<9 {
DispatchQueue.main.asyncAfter(deadline: .now() + Double(1 * index)) {
withAnimation(.easeInOut(duration: 1)) {
let newItem = Item()
self.data.append(newItem)
}
}
}
}
}
Related
I have my animation for the rotation working beautifully, but the image is also moving vertically. Why?
struct SyncView: View {
#State var isSyncing = false
let animation: Animation = Animation.linear(duration: 2.0).repeatForever(autoreverses: false)
var body: some View {
VStack(spacing: 16) {
HStack {
VStack(alignment: .leading) {
Text("Linked Device's Name")
Text("Updating (Last update: Oct 1, 2022)")
.font(.callout)
.foregroundColor(.gray)
}
Spacer()
Text(Image(systemName: "arrow.triangle.2.circlepath"))
.foregroundStyle(Color.yellow)
.font(.title)
.rotationEffect(Angle.degrees(isSyncing ? 360 : 0))
.animation(animation, value: isSyncing)
}
}
.padding()
.onAppear {
isSyncing = true
}
}
}
Try setting the frame of the Text() view to values that make up a square (e.g. 10 x 10). The animation might be trying to center an uneven frame of the image, thus the movement.
I have this LoaderView which grow with given value, I want add some highlight effect to it as well, So basically there is 2 deferent and separate animation happening, one for activeValue and one for the highlight. i did not combine them together because they are 2 deferent things, but my output of codes combine these 2 values together and destroys highlight effect. I am looking a solid answer for my issue to having this 2 animation works side by side.
The issue happens when i add value.
I want this view be usable in macOS as well, so there is a possibility user changes the Window size, then my view would be changed as well.
struct ContentView: View {
#State private var value: CGFloat = 50
var body: some View {
LoaderView(activeValue: value, totalValue: 100)
.padding()
Button("add") { value += 10 }
.padding()
}
}
struct LoaderView: View {
let activeValue: CGFloat
let totalValue: CGFloat
let activeColor: Color
let totalColor: Color
init(activeValue: CGFloat, totalValue: CGFloat, activeColor: Color = Color.green, totalColor: Color = Color.secondary) {
if activeValue >= totalValue { self.activeValue = totalValue }
else if activeValue < 0 { self.activeValue = 0 }
else { self.activeValue = activeValue }
self.totalValue = totalValue
self.activeColor = activeColor
self.totalColor = totalColor
}
#State private var startAnimation: Bool = .init()
private let heightOfCapsule: CGFloat = 5.0
var body: some View {
let linearGradient = LinearGradient(colors: [Color.yellow.opacity(0.1), Color.yellow], startPoint: .leading, endPoint: .trailing)
return GeometryReader { proxy in
totalColor
.overlay(
Capsule()
.fill(activeColor)
.frame(width: (activeValue / totalValue) * proxy.size.width)
.overlay(
Capsule()
.fill(linearGradient)
.frame(width: 100)
.offset(x: startAnimation ? 100 : -100),
alignment: startAnimation ? Alignment.trailing : Alignment.leading)
.clipShape(Capsule()),
alignment: Alignment.leading)
.clipShape(Capsule())
}
.frame(height: heightOfCapsule)
.onAppear(perform: { startAnimation.toggle() })
.animation(Animation.default, value: activeValue)
.animation(Animation.linear(duration: 3.0).repeatForever(autoreverses: false), value: startAnimation)
}
}
The issue isn't the .animations it is that .onAppear is only called once, so your animation never restarts. startAnimation needs to be toggled when activeValue changes. The way your animation works, toggling startAnimation reverses the animation direction. Therefore, I set autoreverses: true. It is a compromise either way.
struct LoaderView: View {
//Nothing changed in this portion
.onAppear{
DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
startAnimation.toggle()
}
}
// The issue is that .onAppear() is only called once.
.onChange(of: activeValue, perform: { _ in
startAnimation.toggle()
})
.animation(Animation.default, value: activeValue)
// As a side effect, changing startAnimation to opposite values reverses the animation
// you have made, so setting autoreverses: true hides this.
.animation(Animation.linear(duration: 3.0).repeatForever(autoreverses: true), value: startAnimation)
}
}
Edit:
I apologize for not getting back to this sooner. The issue with the rubber band animation is because of the transition when the app firsts launches. To prevent this, you need to wrap your variable change in .onAppear() in a DispatchQueue.main.asyncAfter(deadline:) with enough time for the view to load. Then when you start the animation, it works correctly.
I'm making a simple task app and using ForEach to populate task rows with the task information from my model. I need a way to animate my task view to open up and reveal some description text and two buttons. I want to turn from A into B on tap, and then back again on tap:
Design Image
I've tried a couple things. I successfully got a proof-of-concept rectangle animating in a test project, but there are issues. The rectangle shrinks and grows from the centre point, vs. from the bottom only. When I place text inside it, the text doesn't get hidden and it looks really bad.
struct ContentView: View {
#State var animate = false
var animation: Animation = .spring()
var body: some View {
VStack {
Rectangle()
.frame(width: 200, height: animate ? 60 : 300)
.foregroundColor(.blue)
.onTapGesture {
withAnimation(animation) {
animate.toggle()
}
}
}
}
In my main app, I was able to replace my first task view (closed) with another view that's open. This works but it looks bad and it's not really doing what I want. It's effectively replacing the view with another one using a fade animation.
ForEach(taskArrayHigh) { task in
if animate == false {
TaskView(taskTitle: task.title, category: task.category?.rawValue ?? "", complete: task.complete?.rawValue ?? "", priorityColor: Color("HighPriority"), task: task, activeDate: activeDate)
.padding(.top, 10)
.padding(.horizontal)
.onTapGesture {
withAnimation(.easeIn) {
animate.toggle()
}
}
.transition(.move(edge: .bottom))
} else if animate == true {
TaskViewOpen(task: "Grocery Shopping", category: "Home", remaining: 204, completed: 4)
.padding(.top, 10)
.padding(.horizontal)
.onTapGesture {
withAnimation(.easeIn) {
animate.toggle()
}
}
}
Is there a way to animate my original closed view to open up and reveal the description text and buttons?
You are on the right track with your .transition line you have, but you want to make sure that the container stays the same and the contents change -- right now, you're replacing the entire view.
Here's a simple example illustrating the concept:
struct ContentView: View {
#State var isExpanded = false
var body: some View {
VStack {
Text("Headline")
if isExpanded {
Text("More Info")
Text("And more")
}
}
.padding()
.frame(maxWidth: .infinity)
.transition(.move(edge: .bottom))
.background(Color.gray.cornerRadius(10.0))
.onTapGesture {
withAnimation {
isExpanded.toggle()
}
}
}
}
Since you're using it inside a ForEach, you'll probably want to abstract this into its own component, as it'll need its own #State to keep track of the expanded state as I've shown here.
Update, based on comments:
Example of using a PreferenceKey to get the height of the expandable view so that the frame can be animated and nothing fades in and out:
struct ContentView: View {
#State var isExpanded = false
#State var subviewHeight : CGFloat = 0
var body: some View {
VStack {
Text("Headline")
VStack {
Text("More Info")
Text("And more")
Text("And more")
Text("And more")
Text("And more")
Text("And more")
}
}
.background(GeometryReader {
Color.clear.preference(key: ViewHeightKey.self,
value: $0.frame(in: .local).size.height)
})
.onPreferenceChange(ViewHeightKey.self) { subviewHeight = $0 }
.frame(height: isExpanded ? subviewHeight : 50, alignment: .top)
.padding()
.clipped()
.frame(maxWidth: .infinity)
.transition(.move(edge: .bottom))
.background(Color.gray.cornerRadius(10.0))
.onTapGesture {
withAnimation(.easeIn(duration: 2.0)) {
isExpanded.toggle()
}
}
}
}
struct ViewHeightKey: PreferenceKey {
static var defaultValue: CGFloat { 0 }
static func reduce(value: inout Value, nextValue: () -> Value) {
value = value + nextValue()
}
}
Using Swift 5 you can use withAnimation and have the view hidden based on state.
ExpandViewer
Has a button to show and hide the inner view
Takes in a content view
struct ExpandViewer <Content: View>: View {
#State private var isExpanded = false
#ViewBuilder let expandableView : Content
var body: some View {
VStack {
Button(action: {
withAnimation(.easeIn(duration: 0.5)) {
self.isExpanded.toggle()
}
}){
Text(self.isExpanded ? "Hide" : "View")
.foregroundColor(.white)
.frame(maxWidth: .infinity, minHeight: 40, alignment: .center)
.background(.blue)
.cornerRadius(5.0)
}
if self.isExpanded {
self.expandableView
}
}
}
}
Using the viewer
ExpandViewer {
Text("Hidden Text")
Text("Hidden Text")
}
I have a problem with an animation that involves a Text. Basically I need to change the text and animate its position. Take a look at this simple example here below:
import SwiftUI
struct ContentView: View {
#State private var isOn = false
#State private var percentage = 100
var body: some View {
ZStack {
Text("\(percentage)")
.font(.title)
.background(Color.red)
.position(isOn ? .init(x: 150, y: 300) : .init(x: 150, y: 100))
.animation(.easeOut(duration: 1), value: isOn)
VStack {
Spacer()
Button(action: {
self.isOn.toggle()
//just to make the issue happen
if self.percentage == 100 {
self.percentage = 0
} else {
self.percentage = 100
}
}, label: {
Text("SWITCH")
})
}
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
The result is:
There are some issues here. Probably the most annoying is the glitch with the ... I just want to animate the position of the Text, I don't want to animate the text itself and I don't want to animate the width of the text. Any ideas? Thank you.
The possible alternate is to add scaling factor, it supersedes truncation mode and gives different effect, which under some circumstances might be preferable.
The only needed changes is as below (factor modifiable of course)
Text("\(percentage)")
.minimumScaleFactor(0.5)
Try this action on the button:
Button(action:
{
//just to make the issue happen
if self.percentage == 100
{
self.percentage = 0
}
else
{
self.percentage = 100
}
withAnimation(.easeInOut(duration: 1.0)) {
self.isOn.toggle()
}
}, label: {
Text("SWITCH")
})
And remove that line from your Label
.animation(.easeOut(duration: 1), value: isOn)
I didn't test it yet.
I'm drawing a table using SwiftUI that has too many rows and columns to fit into the screen width / height. In this case, I cannot align the view as leading but is somehow always centered. How can I align them top leading?
Here is the view that draws the table:
struct TableView: View {
let columnCount: Int = 9
let rowCount: Int = 14
var body: some View {
VStack(alignment: .leading, spacing: 20) {
ScrollView([.vertical, .horizontal], showsIndicators: false) {
GridStack(rows: self.rowCount, columns: self.columnCount) { row, col in
Text("ROW \(String(row)) COL \(String(col))")
.frame(width: 120)
}
}
}
}
}
And this is GridStack:
struct GridStack<Content: View>: View {
let rows: Int
let columns: Int
let content: (Int, Int) -> Content
var body: some View {
VStack(alignment: .leading) {
ForEach(0 ..< rows) { row in
HStack(alignment: .top) {
ForEach(0 ..< self.columns) { column in
self.content(row, column)
}
}
}
}
.padding([.top, .bottom], 20)
}
init(rows: Int, columns: Int, #ViewBuilder content: #escaping (Int, Int) -> Content) {
self.rows = rows
self.columns = columns
self.content = content
}
}
This is how it looks like in the app. Notice the edges don't fit inside the screen. Even if I try to scroll there, it just bounces back.
Here is a demo of possible approach (and direction of improvements, because I did not test all cases and possibilities)
Note: if you select only one ScrollView axis it does content alignment automatically, otherwise it is now I assume confused, but does not have capability to be configured. So below might be considered as temporary workaround.
The idea is to read grid content offset via GeometryReader recalculation of frame in .global. coordinate space and mitigate it explicitly.
Also there is a try to invalidate and handle offset depending on device orientation (probably not ideal, but as a first try), because they are different.
import Combine
struct TableView: View {
let columnCount: Int = 9
let rowCount: Int = 14
#State private var offset: CGFloat = .zero
private let orientationPublisher = NotificationCenter.default.publisher(for: UIDevice.orientationDidChangeNotification)
var body: some View {
VStack(alignment: .leading, spacing: 20) {
ScrollView([.horizontal, .vertical], showsIndicators: false) {
GridStack(rows: self.rowCount, columns: self.columnCount) { row, col in
Text("ROW \(String(row)) COL \(String(col))")
.fixedSize()
.frame(width: 150)
}
.background(rectReader())
.offset(x: offset)
}
}
.onReceive(orientationPublisher) { _ in
self.offset = .zero
}
}
func rectReader() -> some View {
return GeometryReader { (geometry) -> AnyView in
let offset = -geometry.frame(in: .global).minX
if self.offset == .zero {
DispatchQueue.main.async {
self.offset = offset
}
}
return AnyView(Rectangle().fill(Color.clear))
}
}
}
After several days of trying, finally found a easiest way to solve. Hope this can help.
func body(content: Content) -> some View {
GeometryReader { geo in
ScrollView([.horizontal, .vertical], showsIndicators: true) {
VStack {
ForEach(Range(1...10)) { x in
HStack {
ForEach(Range(1...10)) { y in
Text("\(x), \(y)")
.frame(width: 50, height: 20)
}
Spacer() // 🔑 1
}
}
Spacer() // 🔑 2
}.frame(minWidth: geo.size.width, minHeight: geo.size.height) // 🔑 3
}
}
}