Swift - Animation Direction - ios

I have having a nightmare with a simple problem. On my app I have clouds moving in the background (currently from left to right).
However with the background they need to be right to left.
Eddited for the more of the page code below. Hopefully this will be easier to work out where I have gone wrong.
#IBOutlet var cloud1: UIImageView!
#IBOutlet var cloud2: UIImageView!
#IBOutlet var cloud3: UIImageView!
#IBOutlet var cloud4: UIImageView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func viewWillAppear(_ animated: Bool) {
cloud1.alpha = 0.0
cloud2.alpha = 0.0
cloud3.alpha = 0.0
cloud4.alpha = 0.0
}
override func viewDidAppear(_ animated: Bool) {
UIView.animate(withDuration: 2.0, delay: 0.1,
options: [],
animations: {
self.cloud1.alpha = 1.0
}, completion: nil)
UIView.animate(withDuration: 2.0, delay: 0.1,
options: [],
animations: {
self.cloud2.alpha = 1.0
}, completion: nil)
UIView.animate(withDuration: 2.0, delay: 0.1,
options: [],
animations: {
self.cloud3.alpha = 1.0
}, completion: nil)
UIView.animate(withDuration: 2.0, delay: 0.1,
options: [],
animations: {
self.cloud4.alpha = 1.0
}, completion: nil)
animateTheClouds(cloud: cloud1)
animateTheClouds(cloud: cloud2)
animateTheClouds(cloud: cloud3)
animateTheClouds(cloud: cloud4)
}
func animateTheClouds(cloud : UIImageView) {
let cloudMovingSpeed = 60.0/view.frame.size.width
let duration = (view.frame.size.width - cloud.frame.origin.x) * cloudMovingSpeed
UIView.animate(withDuration: TimeInterval(duration), delay: 0.0, options: .curveLinear, animations: {
// Animate the origin to be off the left side of the screen.
cloud.frame.origin.x = cloud.frame.size.width
}, completion: {_ in
// Reset back to the right edge of the screen
cloud.frame.origin.x = -self.view.frame.size.width
self.animateTheClouds(cloud: cloud)
})

If you want to move them from right to left then you simply need to change the starting and ending x origin.
func animateTheClouds(cloud : UIImageView) {
let cloudMovingSpeed = 60.0/view.frame.size.width
let duration = (cloud.frame.origin.x + cloud.frame.size.width) * cloudMovingSpeed
UIView.animate(withDuration: TimeInterval(duration), delay: 0.0, options: .curveLinear, animations: {
// Animate the origin to be off the left side of the screen.
cloud.frame.origin.x = -cloud.frame.size.width
}, completion: {_ in
// Reset back to the right edge of the screen
cloud.frame.origin.x = self.view.frame.size.width
self.animateTheClouds(cloud: cloud)
})
Also make sure the initial x origin is set to self.view.frame.size.width.

Related

Rotation repetition animation

I'd like to animate a UIImageView left and right. My goal is quite simple:
I have an image, I'd like to rotate it slightly to the left with an angle of .pi/8 and then from that rotated position, rotate it back to -pi/8. I want to repeat these rotations three times and stop. The image has to be in a non-rotated state initially.
I was able to achieve it by doing this:
UIView.animate(withDuration: 0.3, delay: 0.4, options: [], animations: {
self.imageView.rotate(angle: .pi/9)
}, completion: { _ in
UIView.animate(withDuration: 0.3, delay: 0.0, options: [], animations: {
self.imageView.rotate(angle: -.pi/7)
}, completion: { _ in
UIView.animate(withDuration: 0.3, delay: 0.0, options: [], animations: {
self.imageView.rotate(angle: .pi/9)
}, completion: { _ in
UIView.animate(withDuration: 0.3, delay: 0.0, options: [], animations: {
self.imageView.rotate(angle: -.pi/7)
}, completion: { _ in
UIView.animate(withDuration: 0.3, delay: 0.0, options: [], animations: {
self.imageView.rotate(angle: .pi/9)
}, completion: { _ in
UIView.animate(withDuration: 0.3, delay: 0.0, options: [], animations: {
self.imageView.rotate(angle: -.pi/7)
}, completion: {_ in
UIView.animate(withDuration: 0.3, delay: 0.0, options: [], animations: {
self.giftImageView.rotate(angle: .pi/10.5)
})})})})})})})})
However, I believe there is a simpler way to do it but I can't figure it out and the research isn't leading to any simpler solution. After some trial and error, I got to .pi/10.5 to have the image view centered and to not look tilted.
I'd much appreciate your help for a simpler way, thanks!
here is rotation extension function
extension UIView {
func rotation(isClockWise:Bool) {
let rotation : CABasicAnimation = CABasicAnimation(keyPath: "transform.rotation.z")
if isClockWise {
rotation.toValue = NSNumber(value: Double.pi / 8)
} else {
rotation.toValue = NSNumber(value: -Double.pi / 8)
}
rotation.duration = 1 // 1 second duration change it to 0.3 or whatever
rotation.isCumulative = true
rotation.repeatCount = 3
self.layer.add(rotation, forKey: "rotationAnimation")
}
}
then you need to do some work in controller
class ViewController:UIViewController {
var timer = Timer()
var isClockWise = false
var rotationCount = 0
let imageView = UIImageView()
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = .orange
timer = Timer.scheduledTimer(timeInterval: 0.3, target: self, selector: #selector(rotationHandle), userInfo: nil, repeats: true)
}
#objc
func rotationHandle() {
rotationCount += 1
if isClockWise {
imageView.rotation(isClockWise: true)
} else {
imageView.rotation(isClockWise: false)
}
isClockWise.toggle()
if rotationCount == 6 {
timer.invalidate()
imageView.layer.removeAllAnimations()
imageView.transform = .identity
}
}
}

How to fix up animation in swift?

I have UIImageView with moon image.
And moonImageContainerView is a superView for UIImageView
And I added swipe gesture to moonImageContainerView.
If swipe to up,
self.titleLabel.isHidden = false
UIView.animate(withDuration: 0.3, delay: 0.0, options: .curveEaseIn, animations: {
self.moonImageContainerView.transform = CGAffineTransform(scaleX: 0.5, y: 0.5)
self.moonImageContainerView.center.y = self.view.center.y
}, completion: nil)
you can see the result with gif
https://imgur.com/a/ftShkpO
And now, If I add just self.titleLabel.text = "MY TOPIA"
My animation is break.
self.titleLabel.text = "MY TOPIA" // Just added this line.
self.titleLabel.isHidden = false
UIView.animate(withDuration: 0.3, delay: 0.0, options: .curveEaseIn, animations: {
self.moonImageContainerView.transform = CGAffineTransform(scaleX: 0.5, y: 0.5)
self.moonImageContainerView.center.y = self.view.center.y
}, completion: nil)
You can see the result with gif
https://imgur.com/a/y57fPlA
Why does the moonImageContainerView disappear to the bottom?
How can I fix it?
Well, I use the rest setting and did not see your case.
import UIKit
class ImageViewController: UIViewController {
#IBOutlet var moonImageContainerView: UIView!
#IBOutlet var titleLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
let pan = UISwipeGestureRecognizer.init(target: self, action: #selector(pp(_:)))
pan.direction = .up
moonImageContainerView.addGestureRecognizer(pan)
}
#objc func pp(_ pan: UISwipeGestureRecognizer){
self.titleLabel.text = "MY TOPIA"
self.titleLabel.isHidden = false
UIView.animate(withDuration: 0.3, delay: 0.0, options: .curveEaseIn, animations: {
self.moonImageContainerView.transform = CGAffineTransform(scaleX: 0.5, y: 0.5)
self.moonImageContainerView.center.y = self.view.center.y
}, completion: nil)
}
}

.xib Called Inside ViewController Does not Recognize Touch Events

Inside a UIViewController, I call a .xib file and present it over the current UIView.
// initiate the pop up ad view and display it
let popUpAdView = PopUpAdViewController(nibName: "PopUpAdView", bundle: nil)
popUpAdView.displayIntoSuperView(view)
There is a button inside that .xib file that should remove itself from the screen when it's touched. However it doesn't perform so.
What exactly am I missing?
class PopUpAdViewController: UIViewController {
#IBOutlet weak var popUpAdView: UIView!
#IBOutlet weak var closeButton: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
// adjust the view size from the device's screen size
let screenSize = UIScreen.mainScreen().bounds
view.frame = CGRectMake(0, 64, screenSize.width, screenSize.height-64)
// cosmetically adjust the view itself
view.backgroundColor = UIColor.blackColor().colorWithAlphaComponent(0.6)
view.userInteractionEnabled = true
closeButton.userInteractionEnabled = true
// style the pop up ad view
popUpAdView.layer.cornerRadius = 5
popUpAdView.layer.shadowOpacity = 0.8
popUpAdView.layer.shadowOffset = CGSizeMake(0.0, 0.0)
closeButton.addTarget(self, action: #selector(removeOutOfSuperView), forControlEvents: .TouchUpInside)
}
func displayIntoSuperView(superView: UIView!) {
superView.addSubview(self.view)
// define the initial cosmetical values of the items
popUpAdView.transform = CGAffineTransformMakeScale(0.3, 0.3)
popUpAdView.alpha = 0.0
closeButton.alpha = 0.0
// animate...
UIView.animateWithDuration(0.8, delay: 0.0, options: .CurveEaseIn, animations: {
self.popUpAdView.alpha = 1.0
self.popUpAdView.transform = CGAffineTransformMakeScale(1.0, 1.0)
}) { (Bool) in
UIView.animateWithDuration(0.6, delay: 1.5, options: .CurveEaseIn, animations: {
self.closeButton.alpha = 1.0
}, completion: { (Bool) in
})
}
}
func removeOutOfSuperView() {
UIView.animateWithDuration(0.5, delay: 0.0, options: .CurveEaseIn, animations: {
self.closeButton.alpha = 0.0
self.popUpAdView.transform = CGAffineTransformMakeScale(0.1, 0.1)
}) { (finished) in
UIView.animateWithDuration(0.8, delay: 0.0, options: .CurveEaseIn, animations: {
self.view.alpha = 0.0
self.view.removeFromSuperview()
}, completion: nil)
}
}
#IBAction func closePopUpAdView(sender: AnyObject) {
print("Closing the pop up ad...")
removeOutOfSuperView()
}
}
Update
.xib structureL:

Incrementing a parameter in UIView.animateWithDuration in Swift

I have an IBOutlet Collection of buttons that I am trying to present on screen sequentially. They all start off screen fine, but as they animate in, I'd like each button to be presented on screen 0.05 seconds after the previous button. I can't figure out how to increment the delay in UIView.animateWithDuration. With the code below, they are all animating on screen at the same time.
//outlet collection
#IBOutlet var options: [UIButton]!
let increment = 0.25
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
for button in options {
button.center.y += view.bounds.height
}
}
override func viewDidLoad() {
super.viewDidLoad()
for button in options {
UIView.animateWithDuration(1.0, delay: increment, usingSpringWithDamping: 0.7, initialSpringVelocity: 0.0, options: nil, animations: {
button.center.y -= self.view.bounds.height
self.increment + 0.05
}, completion: nil)
}
}
for button in options {
UIView.animateWithDuration(1.0, delay: increment, usingSpringWithDamping: 0.7, initialSpringVelocity: 0.0, options: nil, animations: {
button.center.y -= self.view.bounds.height
}, completion: nil)
}
increment = increment + 0.05
}
Besides:
Change this
let increment = 0.25
To
var increment = 0.25
Increase the increment outside animation. Because animateWithDuration is an async method,it will return first. So,all your button have same delay.
#IBOutlet weak var button1: UIButton!
#IBOutlet weak var button2: UIButton!
#IBOutlet var options: [UIButton]!
let increment = 0.25
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
for button in options {
button.center.y += view.bounds.height
}
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
for button in options {
UIView.animateWithDuration(1.0, delay: increment, usingSpringWithDamping: 0.7, initialSpringVelocity: 0.0, options: nil, animations: {
button.center.y -= self.view.bounds.height
}, completion: nil)
self.increment + 0.05
}
}
Also getting error "Cannot invoke '+=' with an argument list of type '(Double, FloatLiteralConvertible)'" when using += but it will take just +
Here is the way to achieve the required delay between animations:
var i! as UInt64;
i = 0
for button in options {
// your animation with delay
UIView.animateWithDuration(1.0, delay: (i *0.05), usingSpringWithDamping: 0.7, initialSpringVelocity: 0.0, options: nil, animations: {
button.center.y -= self.view.bounds.height
}, completion: nil)
})
++i
}

Swift Continuous Rotation Animation not so continuous

Here is my code. Intent is to continuously rotate the UIImageView named swirls[l]. However, there is a small pause between every rotation start/end. I have gone through every single animation tutorial but cant figure out what the mistake is?
let fullRotation = CGFloat(M_PI * 2)
let duration = 2.0
let delay = 0.0
let options = UIViewKeyframeAnimationOptions.Repeat | UIViewKeyframeAnimationOptions.CalculationModeLinear
UIView.animateKeyframesWithDuration(duration, delay: delay, options: options, animations: {
UIView.addKeyframeWithRelativeStartTime(0, relativeDuration: 1/3, animations: {
swirls[l].transform = CGAffineTransformMakeRotation(1/3 * fullRotation)
})
UIView.addKeyframeWithRelativeStartTime(1/3, relativeDuration: 1/3, animations: {
swirls[l].transform = CGAffineTransformMakeRotation(2/3 * fullRotation)
})
UIView.addKeyframeWithRelativeStartTime(2/3, relativeDuration: 1/3, animations: {
swirls[l].transform = CGAffineTransformMakeRotation(3/3 * fullRotation)
})
}, completion: {finished in
})
EDIT: I see that it has been suggested that a previous solution is available, but it simply does not work for continuous uninterrupted rotation. The only trick that worked for me is the answer that I chose below. Thanks
Try below extension for swift 4.
extension UIView {
func rotate360Degrees(duration: CFTimeInterval = 3) {
let rotateAnimation = CABasicAnimation(keyPath: "transform.rotation")
rotateAnimation.fromValue = 0.0
rotateAnimation.toValue = CGFloat(Double.pi * 2)
rotateAnimation.isRemovedOnCompletion = false
rotateAnimation.duration = duration
rotateAnimation.repeatCount=Float.infinity
self.layer.add(rotateAnimation, forKey: nil)
}
}
For start rotation.
MyView.rotate360Degrees()
And for Stop.
MyView.layer.removeAllAnimations()
You can use UIButton, UILabel and many more.
I'm not sure what's wrong with your code, but I've implemented continuous rotation using this method,
#IBAction func rotateView(sender: UIButton) {
UIView.animate(withDuration: 0.5, delay: 0, options: .curveLinear, animations: { () -> Void in
self.spinningView.transform = self.spinningView.transform.rotated(by: .pi / 2)
}) { (finished) -> Void in
self.rotateView(sender: sender)
}
}
If you want to continuous rotate Button or View and stop that rotation whenever you want then you can try this:
For start rotation:
#IBOutlet weak var RotateBtn: UIButton!
var timeTimer: Timer?
viewDidLoad()
{
self.rotateView()
timeTimer = Timer.scheduledTimer(timeInterval: 0.5, target: self, selector: #selector(self.rotateView), userInfo: nil, repeats: true)
}
func rotateView()
{
UIView.animate(withDuration: 0.5, delay: 0, options: .curveLinear, animations: { () -> Void in
self.RotateBtn.transform = self.RotateBtn.transform.rotated(by: CGFloat(M_PI_4))
})
}
If you want to stop rotation then use:
#IBAction func StopBtn_Pressed(_ sender: AnyObject)
{
timeTimer?.invalidate()
self.RecordBtn.layer.removeAllAnimations()
}

Resources