SwiftUI transition(.asymmetric..) not working with Offset - swift

I am working on a Set Game and I want the cards to swing on the view (from off the screen) via the .transition(.asymmetric(insertion: .offset(x: 100.0, y: 100.0), removal: .offset(x: 100.0, y: 100.0))) command.
Actually, the cards leave the screen by doing exactly the offset, but they just 'appear' at the start on the program rather than actually coming off the screen..
Video of the App
As you can see the Cards that are selected and 'matched' fly off the screen with the .transition(offset).
I would like to see the cards fly in at the beginning of the Game from off the screen in the same manner.
#ViewBuilder
private func body (for size: CGSize) -> some View{
let paddingAllSidesInCards:CGFloat = 8
if card.isFaceUp || !card.isMatched
{
GeometryReader { geo in
VStack(alignment: .center) {
Group
{
ForEach( 0..<card.numberofsymbols)
{ numberofcards in
let cardshape = cardViewModelShape.getShape(Card: card, size: size, numberOfCards: card.numberofsymbols)
cardshape
.transition(.identity)
.aspectRatio(1,contentMode: .fit)
.frame(minWidth: 20, idealWidth: 100, maxWidth: .infinity, minHeight: 20, idealHeight: 100, maxHeight: .infinity, alignment: .center)
.scaleEffect(card.isSelected ? 1.2 : 1)
.animation(.spring(response: (card.isSelected ? 1:0), dampingFraction: 0.1, blendDuration: .infinity))
}.padding(paddingAllSidesInCards)
//Implicit animation - with linear execution
}
}
.cardify(isFaceUp: card.isFaceUp)
}
.transition(.asymmetric(insertion: .offset(x: 100.0, y: 100.0), removal: .offset(x: 100.0, y: 100.0)))
}
}
I am doing something wrong or forgetting a point - I tried the onAppear() operator and it did not work.
Thanks for your help!
PS: If you want to see the full source code, you can check out the repository:
Link SetGame Repo

Provided code is not testable, so just an idea - try to wrap everything into container (it is needed as a placeholder to animate transitions), like
#ViewBuilder
private func body (for size: CGSize) -> some View{
let paddingAllSidesInCards:CGFloat = 8
VStack // << this one !!
{
if card.isFaceUp || !card.isMatched
{
GeometryReader { geo in
VStack(alignment: .center) {
// .. other code
}
.cardify(isFaceUp: card.isFaceUp)
}
.transition(.asymmetric(insertion: .offset(x: 100.0, y: 100.0), removal: .offset(x: 100.0, y: 100.0)))
}
}
.animation(.default) // << use any you want
}

As always the solution was near by - I have placed my animation and transition at the wrong place --> I have tried to place it for each individual card, but actually, I wanted every card at the same time glide in view.
There are different ways to do it and I decided to use a state and an animated offset, so that the cards glide into the view.
struct SetGameView: View {
#ObservedObject var viewModel: SetGameViewModel
#State private var offset = 1000
//var card: SetGameModel<String>.Card
var body: some View {
VStack()
{
Grid(viewModel.cards) { card in
Cardview(cardViewModelShape: viewModel, card: card).onTapGesture
{
withAnimation(.linear(duration: self.AnimationDuration))
{
self.viewModel.choose(card: card)
}
}
}.offset(x: 0.0, y: CGFloat(offset)) // That's important
}

Related

How can make transition stay in own zIndex until ending the transition in SwiftUI?

I have code like this in below:
struct ContentView: View {
#State private var show: Bool = false
var body: some View {
ZStack {
Button("show") { show.toggle() }.foregroundColor(.black)
//.zIndex(1)
if (show) {
Circle()
.fill(.blue)
.frame(width: 100, height: 100)
.transition(AnyTransition.asymmetric(insertion: .offset(x: 0, y: 300), removal: .offset(x: 0, y: 300)))
.onTapGesture { show.toggle() }
//.zIndex(2)
}
}
.frame(width: 300, height: 300)
.padding()
.animation(.linear(duration: 1.5), value: show)
}
}
The issue with this code is that in insertion view stays in correct zIndex(in Top layer) but in removal goes to wrong zIndex(in Bottom layer), I can correct this issue with using direct zIndex but the goal of this question is to find a way without using zIndex modifier, I thing it is possible but not sure how, maybe it has something to do with transition.
This behavior seems like a bug.
I think this is a side effect of the fact that as soon as you remove the Circle() View, it is immediately gone, and the animation happens after the fact. So upon removal, there is instantly just one item in the ZStack and it is on top.
A workaround is to not completely remove a view from the ZStack. This can be accomplished by wrapping the if show { } with an HStack, VStack, or ZStack:
struct ContentView: View {
#State private var show: Bool = false
var body: some View {
ZStack {
Button("show") { show.toggle() }.foregroundColor(.black)
//.zIndex(1)
HStack { // Note: VStack and ZStack also work
if (show) {
Circle()
.fill(.blue)
.frame(width: 100, height: 100)
.transition(AnyTransition.asymmetric(insertion: .offset(x: 0, y: 300), removal: .offset(x: 0, y: 300)))
.onTapGesture { show.toggle() }
//.zIndex(2)
}
}
}
.frame(width: 300, height: 300)
.padding()
.animation(.linear(duration: 1.5), value: show)
}
}
In this case, while the Circle() View is immediately removed, the HStack to which it belongs remains, and it remains in the same position in the ZStack thus fixing the animation.
That said, I'm not sure why adding explicit .zIndex() modifiers helps.
Note: Wrapping if show() { } in a Group does not help because Group is not a View.

SwiftUI - Animate height of rectangle from 0 to height

I am attempting to animate the height of a RoundedRectangle() from 0 to its new height, I would like it to grow from its current position upwards when my device shakes. As it currently stands, I have a onShake function which I want to activate the growing of the rectangle.
struct View1: View {
var body: some View {
ZStack {
Color.white
.edgesIgnoringSafeArea(.all)
Text("Hola")
.foregroundColor(.black)
.font(.headline)
RoundedRectangle(cornerRadius: 5)
.frame(width: 100, height: 0, alignment: .center)
.foregroundColor(Color("RedColour"))
.onShake {
withAnimation {
self.frame(width: 100, height: 100)
}
}
}
}
}
As you can probably tell I am very new to SwiftUI and have very limited knowledge of how animations work. Feel free to grill me for it, but I would also love some help with attempting to grow this rectangle upwards when my device shakes.
Much love!
You could try this. But as the information you provided do not include how you want to use this, this might be incomplete.
struct View1: View {
#State private var height: CGFloat = 0 // add this to modify
// the height of the Rounded Rectangle
let targetHeight: CGFloat = 100 // targetHeight var to syncronise with the VStack
var body: some View {
ZStack {
Color.white
.edgesIgnoringSafeArea(.all)
Text("Hola")
.foregroundColor(.black)
.font(.headline)
.background{
VStack{
Spacer(minLength: 0)
RoundedRectangle(cornerRadius: 5)
.frame(width: 100, height: height)
.foregroundColor(.red)
.onShake {
withAnimation(.linear(duration: 5)) {
height = targetHeight
}
}
}.frame(height: targetHeight) // VStack with fixed height
//to animate from bottom up
}
}
}
}

SwiftUI - How to center a component in a horizontal ScrollView when tapped?

I have a horizontal ScrollView, and within it an HStack. It contains multiple Subviews, rendered by a ForEach. I want to make it so that when these Subviews are tapped, they become centered vertically in the view. For example, I have:
ScrollView(.horizontal) {
HStack(alignment: .center) {
Circle() // for demonstration purposes, let's say the subviews are circles
.frame(width: 50, height: 50)
Circle()
.frame(width: 50, height: 50)
Circle()
.frame(width: 50, height: 50)
}
.frame(width: UIScreen.main.bounds.size.width, alignment: .center)
}
I tried this code:
ScrollViewReader { scrollProxy in
ScrollView(.horizontal) {
HStack(alignment: .center) {
Circle()
.frame(width: 50, height: 50)
.id("someID3")
.frame(width: 50, height: 50)
.onTapGesture {
scrollProxy.scrollTo(item.id, anchor: .center)
}
Circle()
.frame(width: 50, height: 50)
.id("someID3")
.frame(width: 50, height: 50)
.onTapGesture {
scrollProxy.scrollTo(item.id, anchor: .center)
}
...
}
}
But it seemingly had no effect. Does anyone know how I can properly do this?
You can definitely do this with ScrollView and ScrollViewReader. However, I see a couple of things that could cause problems in your code sample:
You use the same id "someID3" twice.
I can't see where your item.id comes from, so I can't tell if it actually contains the same id ("someID3").
I don't know why you have two frames with the same bounds on the same view area. It shouldn't be a problem, but it's always best to keep things simple.
Here's a working example:
import SwiftUI
#main
struct MentalHealthLoggerApp: App {
var body: some Scene {
WindowGroup {
ScrollViewReader { scrollProxy in
ScrollView(.horizontal) {
HStack(alignment: .center, spacing: 10) {
Color.clear
.frame(width: (UIScreen.main.bounds.size.width - 70) / 2.0)
ForEach(Array(0..<10), id: \.self) { id in
ZStack(alignment: .center) {
Circle()
.foregroundColor(.primary.opacity(Double(id)/10.0))
Text("\(id)")
}
.frame(width: 50, height: 50)
.onTapGesture {
withAnimation {
scrollProxy.scrollTo(id, anchor: .center)
}
}
.id(id)
}
Color.clear
.frame(width: (UIScreen.main.bounds.size.width - 70) / 2.0)
}
}
}
}
}
}
Here you can see it in action:
[EDIT: You might have to click on it if the GIF won't play automatically.]
Note that I added some empty space to both ends of the ScrollView, so it's actually possible to center the first and last elements as ScrollViewProxy will never scroll beyond limits.
Created a custom ScrollingHStack and using geometry reader and a bit calculation, here is what we have:
struct ContentView: View {
var body: some View {
ScrollingHStack(space: 10, height: 50)
}
}
struct ScrollingHStack: View {
var space: CGFloat
var height: CGFloat
var colors: [Color] = [.blue, .green, .yellow]
#State var dragOffset = CGSize.zero
var body: some View {
GeometryReader { geometry in
HStack(spacing: space) {
ForEach(0..<15, id: \.self) { index in
Circle()
.fill(colors[index % 3])
.frame(width: height, height: height)
.overlay(Text("\(Int(dragOffset.width))"))
.onAppear {
dragOffset.width = geometry.size.width / 2 - ((height + space) / 2)
}
.onTapGesture {
let totalItems = height * CGFloat(index)
let totalspace = space * CGFloat(index)
withAnimation {
dragOffset.width = (geometry.size.width / 2) - (totalItems + totalspace) - ((height + space) / 2)
}
}
}
}
.offset(x: dragOffset.width)
.gesture(DragGesture()
.onChanged({ dragOffset = $0.translation})
)
}
}
}

How to have text fit within boundaries of circular shape/image SwiftUI

I can't seem to grasp how to make sure that my text overlays and fits within the circular image's boundaries. This is what I have so far.
Circle()
.frame(width: 100, height: 100)
.overlay(
Text("Reaaaallllllyyyyyy Looooooongggggg")
.foregroundColor(Color.red)
.frame(minWidth: 0, maxWidth: .infinity)
)
Is there a way in SwiftUI to get this to work? How would I go about achieving this?
struct ClippedCircleView: View {
#State var text: String = "Reaaaallllllyyyyyy Looooooongggggg"
// Make this any number you are comfortable with
#State var letterLimit: Int = 12
var body: some View {
Circle()
.frame(width: 100, height: 100)
.overlay(
Text(text)
//Limit to 1 line until your letterLimit
.lineLimit(text.count <= letterLimit ? 1 : nil)
//Clips it to shape
.clipShape(ContainerRelativeShape()).padding()
.foregroundColor(Color.red)
//This makes super tiny letters so adjust to your use case
.minimumScaleFactor(0.1)
)
}
}

SwiftUI: How to make entire shape recognize gestures when stroked?

I'm creating a custom button in SwiftUI using some shapes.
As a minimal example, I have a filled rectangle, enclosed by a stroked circle (no fill). This is wrapped in a ZStack and a TapGesture is added to that. It works, but my only issue is that the empty space between the square and the circle is not tappable.
How can I make everything inside the circle tappable, without adding a fill to the circle?
struct ConfirmButton: View {
var action: () -> Void
var body: some View {
ZStack {
Circle()
.stroke(Color.purple, lineWidth: 10.0)
.padding(5)
Rectangle()
.fill(Color.red)
.frame(width: 200, height: 200, alignment: .center)
}.gesture(
TapGesture()
.onEnded {
print("Hello world")
self.action()
}
)
}
}
You need to define the hit area, with modifier .contentShape():
struct ConfirmButton: View {
var action: () -> Void
var body: some View {
ZStack {
Circle()
.stroke(Color.purple, lineWidth: 10.0)
.padding(5)
Rectangle()
.fill(Color.red)
.frame(width: 200, height: 200, alignment: .center)
}.contentShape(Circle())
.gesture(
TapGesture()
.onEnded {
print("Hello world")
self.action()
}
)
}
}