View animating from the incorrect position - swift

I am trying to animate a cover view in my code. Essentially the cover slides up (closes) from off-screen to on-screen, and after the user presses a button the cover slides down (opens up) all the way off-screen.
My code to slide the cover view up the screen and into view is working perfectly. However, the code to slide the cover view down the screen and out of view is not working! The starting position for the cover sliding down is what seems to be incorrect. The cover slides down as expected, but starts far too high, such that the animation ends where it should start.
I've got a screen recording of the error in action (obviously slowed the animation down so you can see what I mean by the error). The cover sliding down should be sliding down from its original position where it slid up to.
Link to recording.
Can anyone spot where I'm going wrong in my code?
func showScoresCover() {
verticalDistance = ScoresCoverView.frame.size.height
self.ScoresCoverView.frame.origin.y += verticalDistance
UIView.animate(
withDuration: 0.5,
delay: 0.25,
options: .curveEaseOut,
animations:
{ self.ScoresCoverView.frame.origin.y -= self.verticalDistance},
completion:
{ finished in
print("Score cover closed.")
})
}
func hideScoresCover() {
verticalDistance = ScoresCoverView.frame.size.height
UIView.animate(
withDuration: 0.5,
delay: 0.25,
options: .curveEaseIn,
animations:
{ self.ScoresCoverView.frame.origin.y += self.verticalDistance},
completion:
{ finished in
print("Score cover opened.")
})
}
EDIT
hey #Nickolans thanks for your help on this issue. So... I have a bizarre update for you on this query. I implemented your code, and it works if I have a pre-programmed button which fires the showScoreCover and hideScoresCover. Turns out even my original code works, but again, only if I have a pre-programmed button which fires the show/hide functions.
However, I need to fire the function using a button where I programmatically reconfigure what the button does. How I've implemented this is through .addTarget and a number of selectors, and those selectors will differ based on where in the game the users are.
Anyway, this is what my code looks like:
self.continueButton.addTarget(self, action: #selector(self.hideScoresCover), for: UIControlEvents.touchUpInside)
self.continueButton.addTarget(self, action: #selector(self.startTeamB), for: UIControlEvents.touchUpInside)
Originally I only used one .addTarget and included the hideScoresCover() in the startTeamB function. This was resulting in the original issue where the cover doesn't hide correctly (starts too high on the screen). So I split it up into the above two .addTargets, and that also results in the same issue. HOWEVER, if I comment out the entire .addTarget line above related to the startTeamB selector and leave the selector related to hideScoresCover, then the cover is shown and is hidden absolutely as I want to to be, the animation is perfect. This means the underlying code in hideScoresCover() is working fine, but that the issue is arising somehow in how hideScoresCover is being run when the continue button is pressed.
Do you have any idea why this would be? somehow that continueButton target is firing incorrectly whenever there are two addTargets, or when there is only one target but hideScoresCover() is included in startTeamB().
I'm stumped as to why this would be the case. startTeamB() is not a complex function at all, so shouldn't be interfering with hideScoresCover(). So this leads me only to conclude it must be the way the continueButton fires hideScoresCover() when its either a separate target in addition to startTeamB being a target, or when hideScoresCover() is included in startTeamB itself. Unusual that it does work correctly when the only .addTarget is a selector calling hidesScoresCover?
#objc func startTeamB() {
self.UpdateTeam() //Just changes the team name
self.TeamBTimer() //Starts a timer to countdown teamB's remaining time
self.TeamAIndicator.isHidden = true //Just hides teamA image
self.TeamBIndicator.isHidden = false //Just shows teamB image
print("Hintify: ","-----Start Team B.")
}

I took it into Xcode and set it up myself. I believe the issue may be how you're changing your Y value, instead of changing the origin change the view layers y position.
The following code works so you can just take it! Make sure to change the frame to whatever you need it to be when you first start.
class ViewController: UIViewController {
//Bool to keep track if view is open
var isOpen = false
var verticalDistance: CGFloat = 0
var ScoresCoverView = UIView()
var button = UIButton()
override func viewDidLoad() {
//Setup Score view
ScoresCoverView.frame = CGRect(x: 0, y: 0, width: view.frame.width, height: view.frame.width)
ScoresCoverView.backgroundColor = .blue
view.addSubview(ScoresCoverView)
//Set vertical distance
verticalDistance = ScoresCoverView.frame.height
//TEST button to test view animations
button.frame = CGRect(x: 200, y: 500, width: 100, height: 100)
button.backgroundColor = .purple
button.addTarget(self, action: #selector(hasBeenFired), for: .touchUpInside)
self.view.addSubview(button)
}
//When button pressed
#objc func hasBeenFired() {
if isOpen {
self.hideScoresCover()
self.isOpen = false
} else {
self.showScoresCover()
self.isOpen = true
}
}
//Show
func showScoresCover() {
self.ScoresCoverView.isHidden = false
UIView.animate(withDuration: 0.5, delay: 0.25, options: .curveEaseOut, animations: {
self.ScoresCoverView.layer.position.y -= self.verticalDistance
}) { (finished) in
print("Score cover closed.")
}
}
//Hide
func hideScoresCover() {
UIView.animate(withDuration: 0.5, delay: 0.25, options: .curveEaseIn, animations: {
self.ScoresCoverView.layer.position.y += self.verticalDistance
}) { (finished) in
self.ScoresCoverView.isHidden = true
print("Score cover Opened.")
}
}
}
EDIT
If you'd like to change the functionality of the button, make sure to remove the previous target before adding a new one.
For example, if you want to switch from show/hide to teamB remove show/hide and add teamB-- and vice versa.
When you first start, add your initial target:
self.continueButton.addTarget(self, action: #selector(self.hideScoresCover), for: UIControlEvents.touchUpInside)
Switch to startTeamB:
self.continueButton.removeTarget(self, action: #selector(self.hideScoresCover), for: UIControlEvents.touchUpInside)
self.continueButton.addTarget(self, action: #selector(self.startTeamB), for: UIControlEvents.touchUpInside)
Switch to hideScoreCover:
self.continueButton.removeTarget(self, action: #selector(self.startTeamB), for: UIControlEvents.touchUpInside)
self.continueButton.addTarget(self, action: #selector(self.hideScoresCover), for: UIControlEvents.touchUpInside)

I just want to say one thing, maybe the += is not necessary here.
func showScoresCover() {
verticalDistance = ScoresCoverView.frame.size.height
self.ScoresCoverView.frame.origin.y += verticalDistance
UIView.animate(
withDuration: 0.5,
delay: 0.25,
options: .curveEaseOut,
animations:
{ self.ScoresCoverView.frame.origin.y -= self.verticalDistance},
completion:
{ finished in
print("Score cover closed.")
})
}
should be
`self.ScoresCoverView.frame.origin.y = verticalDistance`

Related

Transform collection view cell container after Swipe to right and left

I'm trying to add Swipe to right and left to collection view cell to transform the container to the right and left with a certain angle
Here is my initial setup
private func setupGestures() {
let swipeToRight = UISwipeGestureRecognizer(target: self, action: #selector(respondToSwipeRight))
swipeToRight.direction = .right
container.addGestureRecognizer(swipeToRight)
let swipeToLeft = UISwipeGestureRecognizer(target: self, action: #selector(respondToSwipeLeft))
swipeToLeft.direction = .left
container.addGestureRecognizer(swipeToLeft)
}
#objc func respondToSwipeRight(gesture: UIGestureRecognizer) {
let angle = CGFloat(Double.pi/2)
UIView.animate(withDuration: 0.5) {
self.container.transform = CGAffineTransform(rotationAngle: angle)
}
}
#objc func respondToSwipeLeft(gesture: UIGestureRecognizer) {
let angle = -CGFloat(Double.pi/2)
UIView.animate(withDuration: 0.5) {
self.container.transform = CGAffineTransform(rotationAngle: angle)
}
}
But it completely rotate the container, which is I don't want, I want to make it something like it, and turn back to it's initial position after a sec or two
[![how it should transform][1]][1]
And it would be so awesome that move based on Swiping position, I mean not automatically goes to that level of position, move with finger tip and when it reach there, just stop moving.
Could anyone help me to implement it, I have no idea how I can do it
Many thanks
Adding completion in UIView.animate in order to turn back to initial state. After a sec or two is depends on your duration in UIView.animate
Code will be like this
UIView.animate(withDuration: 0.5, animations: {
self.container.transform = CGAffineTransform(rotationAngle: 0.5)
}, completion: {
_ in
// turn back to the previous before transform
self.container.transform = .identity
})
And for your second question, you can implement with touchesBegan and touchesMoved or add PanGesture to handle changing position container view frame like you want.

When I scroll my UIScrollView, animations that are connected to a timer and animate views inside of the scrollview, suddenly stop ticking

I have a UIScrollView containing views, which are connected to timers that call a function every x seconds. Everything works perfectly, until I start scrolling the scroll view, upon which the timers stop ticking, meaning that the animations stop happening. I do not know if this is clear enough, but I will show you some code below to try to clarify.
#objc func lowBeatingAnimation(){
for i in lowWindow{
let List = i as? [Any] ?? []
let View = List[0] as! UIView
let width = List[1] as! NSLayoutConstraint
let height = List[2] as! NSLayoutConstraint
let label = List[3] as! UILabel
self.view.layoutIfNeeded()
UIView.animate(withDuration: 0.5, delay: 0, options: .curveEaseIn, animations: {
View.layer.shadowRadius = 50
width.constant += -20
height.constant += -20
label.alpha = 0.65
View.layer.cornerRadius += -10
self.view.layoutIfNeeded()
}, completion: { finished in
UIView.animate(withDuration: 0.5, delay: 0, options: .curveEaseOut, animations: {
View.layer.shadowRadius = 10
width.constant += 20
View.layer.cornerRadius += 10
label.alpha = 0.85
height.constant += 20
self.view.layoutIfNeeded()
}, completion: { finished in
})
})
}
}
That is the function I call every second. lowWindow is an array, consisting of arrays with the following format: [UIView, NSLayoutConstraint (belonging to the first element in the list), NSLayoutConstraint (also belonging to the first element in the list), UILabel]
The first element in lowWindow is a UIView, which is a subview of the scroll view, which causes the animation to stop whenever it gets scrolled.
I think the issue can be boiled down to the following question, although I am not entirely sure: Why does an external timer stop working whenever the position of the scrollview gets edited?
I have also tried different things in terms of whether the views that get animated are direct subviews of the scrollview, or if they are subviews of a subview of the scrollview. Nothing works so far. If you have any ideas on how to solve this and would like to share it, that would be highly appreciated. Thanks.
I solved this by adding the timers to Runloop.
RunLoop.main.add(lowTimer, forMode: .common)
RunLoop.main.add(mediumTimer, forMode: .common)
RunLoop.main.add(highTimer, forMode: .common)

UIDatePicker's Change Year Arrow's Animation Transition

What is the animation transition used in the right-arrow image to the down-arrow image when changing the year in the UIDatePicker control? The animation smoothly rotates the start image to the end image like so:
I am trying to mimic this transition for an image in my code. In viewDidLoad(), I have:
myButton.setImage(UIImage(named: "rightArrow")?.withRenderingMode(.alwaysTemplate), for: .normal)
and then within the function invoked when that button is tapped, I do:
UIView.transition(with: myButton, duration: 0.6, options: .transitionCrossDissolve, animations: {
self.myButton.setImage(UIImage(named: "downArrow")?.withRenderingMode(.alwaysTemplate), for: .normal)
}, completion: nil)
I am using .transitionCrossDissolve here, but obviously it isn't the right transition. I tried each of the seven available transition options, but none of them behave like in UIDatePicker. Is there an easy way to create this "rotating" transition?
I finally figured it out. This will animate the rotation of the arrow:
UIView.transition(with: myButton, duration: 0.2, options: [], animations: {
self.myButton.transform = CGAffineTransform(rotationAngle: .pi/2)
}, completion: nil)
EDIT -- shorter solution:
UIView.animate(withDuration: 0.2) {
self.myButton.transform = CGAffineTransform(rotationAngle: .pi/2)
}

Asynchronous Function with DispatchGroup

I'm trying to set an animation inside of Playgrounds and make a simple message pop up in the debugger after completion.
With this, the .notify is appearing at the beginning. Wouldn't it appear after the animate functions went through inside of DispatchQueue.main.async(group: animationGroup)?
Here is the code provided:
import UIKit
import PlaygroundSupport
PlaygroundPage.current.needsIndefiniteExecution = true
extension UIView {
static func animate(withDuration duration: TimeInterval, animations: #escaping () -> Void, group: DispatchGroup, completion: ((Bool) -> Void)?) {
}
}
let animationGroup = DispatchGroup()
// A red square
let view = UIView(frame: CGRect(x: 0, y: 0, width: 200, height: 200))
view.backgroundColor = UIColor.red
// A yellow box
let box = UIView(frame: CGRect(x: 0, y: 0, width: 40, height: 40))
box.backgroundColor = UIColor.yellow
view.addSubview(box)
PlaygroundPage.current.liveView = view
DispatchQueue.main.async(group: animationGroup) {
UIView.animate(withDuration: 1, animations: {
// Move box to lower right corner
box.center = CGPoint(x: 150, y: 150)
}, completion: {
_ in
UIView.animate(withDuration: 2, animations: {
// Rotate box 45 degrees
box.transform = CGAffineTransform(rotationAngle: .pi/4)
}, completion: .none)
})
UIView.animate(withDuration: 4, animations: { () -> Void in
// Change background color to blue
view.backgroundColor = UIColor.blue
})
}
animationGroup.notify(queue: DispatchQueue.main) {
print("Animations Completed!")
}
The call to async(group:os:flags:execute:) API that you’re using is used when performing tasks that are, themselves, synchronous. E.g. let's say you were going to process a bunch of images in some slow, synchronous API, but wanted to run this in parallel, on background threads to avoid blocking the main thread. Then you’d use async(group:execute:) API:
let group = DispatchGroup()
for image in images {
DispatchQueue.global().async(group: group) {
self.process(image)
}
}
group.notify(queue: .main) {
// all done processing the images
}
In this case, though, the individual, block-based UIView animation API calls run asynchronously. So you can’t use this async(group:execute:) pattern. You have to manually enter before starting each asynchronous process and then leave inside the respective completion closures, matching them up one-to-one:
animationGroup.enter()
UIView.animate(withDuration: 1, animations: {
box.center = CGPoint(x: 150, y: 150) // Move box to lower right corner
}, completion: { _ in
UIView.animate(withDuration: 2, animations: {
box.transform = CGAffineTransform(rotationAngle: .pi / 4) // Rotate box 45 degrees
}, completion: { _ in
animationGroup.leave()
})
})
animationGroup.enter()
UIView.animate(withDuration: 4, animations: {
view.backgroundColor = .blue // Change background color to blue
}, completion: { _ in
animationGroup.leave()
})
animationGroup.notify(queue: .main) {
print("Animations Completed!")
}
First of all, to quote from the documentation:
notify(queue:work:)
Schedules a work item to be submitted to a queue when a group of previously submitted block objects have completed.
Basically, there are no "previously" submitted blocks, so your notify block is called right away. This is happening because you added work items to the group in DispatchQueue.main.async. You can check this by adding a print inside DispatchQueue.main.async(group: animationGroup) and another print right before you call the notify method. The second one will print first.
On top of that, calling an asynchronous function inside DispatchGroup.main.async is problematic because the work item will enter immediately, then you'll dispatch your async work to another thread, and the work item will leave right after, even though your async work isn't done.
To fix this, you have to call animationGroup.enter() when you start your asynchronous operation, and then call animationGroup.leave() when you're done. Additionally, you have to take your code out of DispatchGroup.main.async. If you make these changes, the notify block will execute when the enter/leave calls are balanced.

Swift contentOffset scroll

I am developing a small application for tvOS where I need to show a UITextView.
Unfortunately sometimes this text can't fit inside the screen, that's why I need a way to scroll to the bottom of it programmatically.
I've tried using the following code:
self.setContentOffset(offset, animated: true)
It's actually working as intended, except for the fact that I need to handle the animation speed, so that the user can actually read; at the moment it's too fast.
This is what I tried to do, but with little success:
let offset = CGPoint(x: 0, y: contentSize.height - bounds.size.height)
UIView.animate(withDuration: 4, animations: {
self.setContentOffset(offset, animated: false)
})
I need a way to keep the text in place and scroll it to show the missing lines.
I am using a UITextView inside an UIScrollView.
Thanks.
If anyone is looking for a solution, this is what I ended up using:
var textTopDistance = 100
//calculate height of the text not being displayed
textNotVisibleHeight = descriptionLabel.contentSize.height - scrollView.bounds.size.height
func scrollText() {
//start new thread
DispatchQueue.main.async() {
//animation
UIView.animate(withDuration: 6, delay: 2, options: UIViewAnimationOptions.curveLinear, animations: {
//set scrollView offset to move the text
self.scrollView.contentOffset.y = CGFloat(self.textNotVisibleHeight - self.textTopDistance)
}, completion: nil)
}
}
It's not perfect I know, but at least it's working as intended.