SwiftUI Swipe/Drag over NavigationLink - swift

I want to be able to update a view with a swipe left/right over a NavigationView that has multiple NavigationLinks in it. The NavigationLinks go to different presentation views.
When I begin the Drag gesture on the outer most view, if that gesture begins over a NavigationLink, the link changes color as though it has been pressed. Continuing the drag gesture, the main view does update as expected and the NavigationLink returns to it's normal state (color).
What I need is a way to have the NavigationLink NOT change color when it is a drag gesture that is occuring. Maybe a way to have the NavigationLink react "if" the touch is a long touch or something.
Here is some code that demonstrates what I am seeing. This is not my actual project, but a very stripped down example.
Any suggestions or solutions appreciated!
import SwiftUI
struct ContentView: View {
#State var outputText: String = ""
var body: some View {
VStack(alignment: .center, spacing: 20) {
NavigationView {
VStack {
Text("Navigation View")
NavigationLink(destination: Text("Showwing Widget")) {
HStack {
Text("Navigation Link")
}
.frame(width: 300, height: 200)
.border(Color.blue)
}
.border(Color.red)
Spacer()
}
.border(Color.yellow)
}
Text(outputText)
.font(.title)
.fontWeight(.bold)
Text("My Green Oval")
.foregroundColor(.white)
.fontWeight(.bold)
.font(.title)
.frame(width: 300, height: 200)
.background(
Ellipse()
.fill(Color.green)
)
Button(action: {
outputText = "Button tapped"
}) {
Text("Button to Tap")
}
Text("Just some words...")
Spacer()
}
.highPriorityGesture(DragGesture(minimumDistance: 25, coordinateSpace: .local)
.onEnded { value in
if abs(value.translation.height) < abs(value.translation.width) {
if abs(value.translation.width) > 50.0 {
if value.translation.width < 0 {
self.swipeRightToLeft()
} else if value.translation.width > 0 {
self.swipeLeftToRight()
}
}
}
}
)
}
func swipeRightToLeft() {
outputText = "Swiped Right to Left <--"
}
func swipeLeftToRight() {
outputText = "Swiped Left to Right -->"
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}

After toying around forever I have a solution here! Hacky maybe, but it works with little effort. Configure your view with an offset that is conditional on whether your drawer row is open or not and also create a state variable to keep track on whether or not your user is dragging. You can get the screenWidth by using UIScreen.main.bounds.width.
.offset(x: self.isOpen ? -screenWidth/12 : 0, y: 0)
.simultaneousGesture(DragGesture()
.onChanged{ gesture in
self.isDragging = true
self.offset = gesture.translation.width
}
.onEnded { _ in
self.isDragging = false
if self.offset > 0 {
withAnimation {
self.isOpen = false
self.offset = 0
}
} else if self.offset < 0 {
withAnimation {
self.isOpen = true
self.offset = 0
}
}
})
Then add this disable modifier on your NavigationLink
.disabled(self.isDragging || self.isOpen)
Good luck! Hopefully this works for you as well if you haven't found a solution.

Related

ZStack blocks animation SwiftUI

So my goal is to be able to show a custom view from time to time over a SwiftUI tabview, so I thought I would place them both in a ZStack like this
#State var show = true
#State private var selectedTab : Int = 0
var body: some View {
ZStack {
TabView(selection: $selectedTab) {
Color.pink
}
if show {
Button(action: {
withAnimation(Animation.linear(duration: 10)) {
show = false
}
}) {
Color.blue
}
.frame(width: 100, height: 100)
}
}
}
This works just fine, but when I try to use withAnimation() no animation gets triggered. How can I make the overlaying view, disappear with animation?
Use .animation modifier with container, like below, so container could animate removing view
ZStack {
TabView(selection: $selectedTab) {
Color.pink
}
if show {
Button(action: {
show = false // << withAnimation not needed anymore
}) {
Color.blue
}
.frame(width: 100, height: 100)
}
}
.animation(Animation.linear(duration: 10), value: show) // << here !!
So I found a solution and what I think is the cause of this. My hypothesis is that the animation modifier does not handle ZIndex IF it is not explicitly set.
One solution to this is to set ZIndex to the view that should be on the top to something higher than the other view. Like this:
#State var show = true
#State private var selectedTab : Int = 0
var body: some View {
ZStack {
TabView(selection: $selectedTab) {
Color.pink
}
if show {
Button(action: {
withAnimation {
show = false
}
}) {
Color.blue
}
.frame(width: 100, height: 100)
.zIndex(.infinity) // <-- this here makes the animation work
}
}
}

TabView Indicator doesn't move when page changes

When I scroll from one page to the other the horizontal indicator bar doesn't move, what would be the appropriate way to move it (with animation if possible)?
The green area below doesn't move to the right once I switch to the analytics area.
Here's the full code:
enum PortfolioTabBarOptions: Hashable, CaseIterable {
case balance, analytics
var menuString: String { String(describing: self) }
}
struct CustomPagerTabView: View {
#Binding var selectedTab: PortfolioTabBarOptions
#State var tabOffset: CGFloat = 0
var body: some View {
VStack {
HStack(alignment: .center) {
HStack(spacing: 100) {
ForEach(Array(PortfolioTabBarOptions.allCases.enumerated()), id: \.element) { index, element in
// Current Tab
if(selectedTab.menuString == element.menuString) {
Text(element.menuString.capitalizeFirstLetter())
.font(.system(size: 15.0))
.bold()
.onTapGesture() {
selectedTab = element.self
}
.onAppear {
self.tabOffset = CGFloat(index)
}
}
// Innactive Tabs
else {
Text(element.menuString.capitalizeFirstLetter())
.foregroundColor(.gray)
.font(.system(size: 15.0))
.bold()
.onTapGesture() {
selectedTab = element.self
}
}
}
}
.padding(.horizontal)
}
// Indicator...
Capsule()
.fill(.gray)
// Width of the indicator bar
.frame(width: PortfolioTabBarOptions.allCases.count == 0 ? 0 : (getScreenBounds().width / CGFloat(PortfolioTabBarOptions.allCases.count)), height: 1.2)
.padding(.top,10)
.frame(maxWidth: .infinity,alignment: .leading)
.offset(x: tabOffset)
}
.padding(.top)
}
}
The green area below does move to the right, but only 1 pixel. Try something like this example code, choose the value (200) most suited for your purpose:
.onAppear {
self.tabOffset = CGFloat(index*200) // <-- here
}

Animating a flashing bell in SwiftUI

I am having problems with making a simple systemIcon flash in SwiftUI.
I got the animation working, but it has a silly behaviour if the layout of
a LazyGridView changes or adapts. Below is a video of its erroneous behaviour.
The flashing bell stays in place but when the layout rearranges the bell
starts transitioning in from the bottom of the parent view thats not there anymore.
Has someone got a suggestion how to get around this?
Here is a working example which is similar to my problem
import SwiftUI
struct FlashingBellLazyVGrid: View {
#State var isAnimating = false
#State var showChart = true
var body: some View {
let columns = [GridItem(.adaptive(minimum: 300), spacing: 50, alignment: .center)]
VStack {
Button(action: {
showChart.toggle()
}) {
VStack {
Circle()
.fill(showChart ? Color.green : Color.red)
.shadow(color: Color.gray, radius: 5, x: 2, y: 2)
Text("Charts")
.foregroundColor(Color.primary)
}.frame(width: 150, height: 50)
}
ScrollView {
LazyVGrid (
columns: columns, spacing: 50
) {
ForEach(0 ..< 25) { item in
ZStack {
Rectangle()
.fill(Color.red)
.cornerRadius(15)
VStack {
HStack {
Text(/*#START_MENU_TOKEN#*/"Hello, World!"/*#END_MENU_TOKEN#*/)
Spacer()
Image(systemName: "bell.fill")
.foregroundColor(Color.yellow)
.opacity(self.isAnimating ? 1 : 0)
.animation(Animation.easeInOut(duration: 0.66).repeatForever(autoreverses: false))
.onAppear{ self.isAnimating = true }
}.padding(50)
if showChart {
Rectangle()
.fill(Color.green)
.frame(height: 200)
}
}
}
}
}
}
}
}
}
struct FlashingBellLazyVGrid_Previews: PreviewProvider {
static var previews: some View {
FlashingBellLazyVGrid()
}
}
how it looks like before you click the showChart button at the top
After you toggle the button it looks like the bells are erroneously moving into place from the bottom of the screen. and toggling it back to its original state doesn't resolve this bug subsequently.
[
Looks like the animation is basing itself off of the original size of the view. In order to trick it into recognizing the new view size, I used .id(UUID()) on the outside of the grid. In a real world application, you'd probably want to be careful to store this ID somewhere and only refresh it when needed -- not on every re-render like I'm doing:
struct FlashingBellLazyVGrid: View {
#State var showChart = true
let columns = [GridItem(.adaptive(minimum: 300), spacing: 50, alignment: .center)]
var body: some View {
VStack {
Button(action: {
showChart.toggle()
}) {
VStack {
Circle()
.fill(showChart ? Color.green : Color.red)
.shadow(color: Color.gray, radius: 5, x: 2, y: 2)
Text("Charts")
.foregroundColor(Color.primary)
}.frame(width: 150, height: 50)
}
ScrollView {
LazyVGrid (
columns: columns, spacing: 50
) {
ForEach(0 ..< 25) { item in
ZStack {
Rectangle()
.fill(Color.red)
.cornerRadius(15)
VStack {
SeparateComponent()
if showChart {
Rectangle()
.fill(Color.green)
.frame(height: 200)
}
}
}
}
}
.id(UUID()) //<-- Here
}
}
}
}
struct SeparateComponent : View {
#State var isAnimating : Bool = false
var body: some View {
HStack {
Text("Hello, World!")
Spacer()
Image(systemName: "bell.fill")
.foregroundColor(Color.yellow)
.opacity(self.isAnimating ? 1 : 0)
.animation(Animation.easeInOut(duration: 0.66).repeatForever(autoreverses: false))
.onAppear{
self.isAnimating = true
}
}
.padding(50)
}
}
I also separated out the blinking component into its own view, since there were already problematic things happening with the existing logic with onAppear, which wouldn't affect newly-scrolled-to items correctly. This may need refactoring for your particular case as well, but this should get you started.

Conditional animation in SwiftUI stops working

I have this code:
Group{
if self.done{
Image(systemName: "plus").font(.system(size: 40)).foregroundColor(.gray)
.padding().overlay(Circle().stroke(Color.gray, lineWidth: 3)).opacity(0.6)
}
else{
Button(action: {self.showSearchTrash = 1}){
Image(systemName: "plus").font(.system(size: 40)).foregroundColor(green)
.padding().overlay(Circle().stroke(green, lineWidth: 3).scaleEffect(1+self.animationAmount).animation(Animation.easeInOut(duration: 1).repeatForever(autoreverses: true)).onAppear {self.animationAmount = 0.1})
}
}
}.padding(.bottom, 5)
And the intention is that if self.done is false, the circle on the plus button will expand and contract indefinitely.
This works. However, if I use a toggle to set self.done to be true and then turn it back to false, the animation no longer occurs. I know that the issue is not with the toggle, because it does return to being green.
Also, the lack of . before green is intentional - I defined a specific Color green.
Any idea why the animation stops working/how to fix this?
Actually works fine as-is with Xcode 12.1 / iOS 14.1, so you might observe either bug of new iOS version or result of some other code.
Anyway, I would added turn-offs scaling on button disappear:
Button(action: {}){
Image(systemName: "plus").font(.system(size: 40)).foregroundColor(green)
.padding().overlay(Circle().stroke(green, lineWidth: 3).scaleEffect(1+self.animationAmount).animation(Animation.easeInOut(duration: 1).repeatForever(autoreverses: true)))
}
.onAppear {self.animationAmount = 0.1} // << put here !!
.onDisappear {self.animationAmount = 0} // << add this !!
You can specify Animation in the withAnimation block and create separate functions for starting/stopping the animation.
Here is a possible solution:
struct ContentView: View {
#State private var done = false
#State private var animationAmount: CGFloat = 0
var body: some View {
VStack {
Toggle("Done", isOn: $done)
plusImage
.opacity(done ? 0.6 : 1)
.foregroundColor(done ? .gray : .green)
}
.onAppear(perform: startAnimation)
.onChange(of: done) { done in
if done {
stopAnimation()
} else {
startAnimation()
}
}
}
var plusImage: some View {
Image(systemName: "plus")
.font(.system(size: 40))
.padding()
.overlay(
Circle()
.stroke(Color.gray, lineWidth: 3)
.scaleEffect(1 + animationAmount)
)
}
}
private extension ContentView {
func startAnimation() {
withAnimation(Animation.easeInOut(duration: 1).repeatForever()) {
animationAmount = 0.1
}
}
func stopAnimation() {
withAnimation {
animationAmount = 0
}
}
}

Transition with a view with SwiftUI without animating the entire view

Using SwiftUI, I have a view that includes a slider that I'm using a transition to slide in from the bottom. All works well, until the slider is moved quickly back and forth. With that, the text field is being animated, and will show "..." when changing from 1 to two digits.
Here is my test code showing this:
struct TestSliderView: View {
#State private var val: Double = 0
#State private var showSlider: Bool = false
var body: some View {
VStack {
Button(action: {
self.showSlider.toggle()
}) {
Text("Show Slider")
}
Spacer()
if showSlider {
JustTheSlider(val: $val)
.padding()
.transition(.move(edge: .bottom))
.animation(.linear(duration: 0.4))
}
}
}
}
struct JustTheSlider: View {
#Binding var val: Double
var body: some View {
VStack {
Text("Slider")
.font(.title)
HStack {
Text("Value: ")
.frame(minWidth: 80, alignment: .leading)
Slider(value: $val, in: 0...30, step: 1)
Text("\(Int(val))")
.frame(minWidth: 20, alignment: .trailing)
.font(Font.body.monospacedDigit())
.padding(.horizontal)
}
}
}
}
One way around this would be to remove the .animation(.linear(duration: 0.4)) line and wrap the button action with an animation like so:
Button(action: {
withAnimation(.linear(duration: 0.4)) {
self.showSlider.toggle()
}
}) {
Text("Show Slider")
}
This stops the text from animating, but then the view only slides out, and just pops in without any slide animation.
Any ideas?
You need animate the state variable, not the View.
var body: some View {
VStack {
Button(action: {
withAnimation{
self.showSlider.toggle()}
}) {
Text("Show Slider")
}
Spacer()
if showSlider {
JustTheSlider(val: $val)
.padding()
.transition(.move(edge: .bottom))
}
}
}
As the last line shown.