I have a UILabel with background color as grey.
I want a blinking effect on this label like it should become a little white & then become gray and it should keep happen till I turn it off programatically.
Any clue how to achieve this?
You can do this within a block:
self.yourLabel.alpha = 1;
[UIView animateWithDuration:1.5 delay:0.5 options:UIViewAnimationOptionRepeat | UIViewAnimationOptionAutoreverse animations:^{
self.yourLabel.alpha = 0;
} completion:nil];
So you dont need a second method.
Swift 3
extension UILabel {
func startBlink() {
UIView.animate(withDuration: 0.8,
delay:0.0,
options:[.allowUserInteraction, .curveEaseInOut, .autoreverse, .repeat],
animations: { self.alpha = 0 },
completion: nil)
}
func stopBlink() {
layer.removeAllAnimations()
alpha = 1
}
}
You can simply make an extension to the UILabel class that will support the blinking effect. I don't think using a timer is a right approach since you won't have any fade effect.
Here is the Swift way to do this:
extension UILabel {
func blink() {
self.alpha = 0.0;
UIView.animateWithDuration(0.8, //Time duration you want,
delay: 0.0,
options: [.CurveEaseInOut, .Autoreverse, .Repeat],
animations: { [weak self] in self?.alpha = 1.0 },
completion: { [weak self] _ in self?.alpha = 0.0 })
}
}
Swift 3:
extension UILabel {
func blink() {
self.alpha = 0.0;
UIView.animate(withDuration: 0.8, //Time duration you want,
delay: 0.0,
options: [.curveEaseInOut, .autoreverse, .repeat],
animations: { [weak self] in self?.alpha = 1.0 },
completion: { [weak self] _ in self?.alpha = 0.0 })
}
}
EDIT Swift 3: Works for almost any view
extension UIView {
func blink() {
self.alpha = 0.0;
UIView.animate(withDuration: 0.8, //Time duration you want,
delay: 0.0,
options: [.curveEaseInOut, .autoreverse, .repeat],
animations: { [weak self] in self?.alpha = 1.0 },
completion: { [weak self] _ in self?.alpha = 0.0 })
}
}
Use NSTimer
NSTimer *timer = [NSTimer
scheduledTimerWithTimeInterval:(NSTimeInterval)(1.0)
target:self
selector:#selector(blink)
userInfo:nil
repeats:TRUE];
BOOL blinkStatus = NO;
in your blink function
-(void)blink{
if(blinkStatus == NO){
yourLabel.backgroundColor = [UIColor whiteColor];
blinkStatus = YES;
}else {
yourLabel.backgroundColor = [UIColor grayColor];
blinkStatus = NO;
}
}
A different approach but works. Blinking only for 3 seconds
extension UIView {
func blink() {
let animation = CABasicAnimation(keyPath: "opacity")
animation.isRemovedOnCompletion = false
animation.fromValue = 1
animation.toValue = 0
animation.duration = 0.8
animation.autoreverses = true
animation.repeatCount = 3
animation.beginTime = CACurrentMediaTime() + 0.5
self.layer.add(animation, forKey: nil)
}
}
Rather use the view animations. It makes it very simple and is easy to control. Try this:
self.yourLabel.alpha = 1.0f;
[UIView animateWithDuration:0.12
delay:0.0
options:UIViewAnimationOptionCurveEaseInOut |
UIViewAnimationOptionRepeat |
UIViewAnimationOptionAutoreverse |
UIViewAnimationOptionAllowUserInteraction
animations:^{
self.yourLabel.alpha = 0.0f;
}
completion:^(BOOL finished){
// Do nothing
}];
You can tweak the values to get different effects for example, changing animateWithDuration wil set the blinking speed. Further you can use it on anything that inherits from UIView example a button, label, custom view etc.
Tweaking Krishnabhadra Answer to give a better blink effect
Declare a Class variable bool blinkStatus;
And paste code given below
NSTimer *yourtimer = [NSTimer scheduledTimerWithTimeInterval:(NSTimeInterval)(10.0 / 60.0) target:self selector:#selector(blink) userInfo:nil repeats:TRUE];
blinkStatus = FALSE;
-(void)blink{
if(blinkStatus == FALSE){
yourLabel.hidden=NO;
blinkStatus = TRUE;
}else {
yourLabel.hidden=YES;
blinkStatus = FALSE;
}
}
-(void) startBlinkingLabel:(UILabel *)label
{
label.alpha =1.0f;
[UIView animateWithDuration:0.32
delay:0.0
options: UIViewAnimationOptionAutoreverse |UIViewAnimationOptionRepeat | UIViewAnimationOptionCurveEaseInOut | UIViewAnimationOptionAllowUserInteraction |UIViewAnimationOptionBeginFromCurrentState
animations:^{
label.alpha = 0.0f;
}
completion:^(BOOL finished){
if (finished) {
}
}];
}
-(void) stopBlinkingLabel:(UILabel *)label
{
// REMOVE ANIMATION
[label.layer removeAnimationForKey:#"opacity"];
label.alpha = 1.0f;
}
My swift version based on Flex Elektro Deimling's answer:
private func startTimeBlinkAnimation(start: Bool) {
if start {
timeContainerView.alpha = 1
UIView.animateWithDuration(0.6, delay: 0.3, options:[.Repeat, .Autoreverse], animations: { _ in
self.timeContainerView.alpha = 0
}, completion: nil)
}
else {
timeContainerView.alpha = 1
timeContainerView.layer.removeAllAnimations()
}
}
Got stuck when trying with swift and using multiple options but this seems to work nicely:
self.cursorLabel.alpha = 1
UIView.animate(withDuration: 0.7, delay: 0.0, options: [.repeat, .autoreverse, .curveEaseInOut], animations: {
self.cursorLabel.alpha = 0
}, completion: nil)
This is how it worked for me. I adapted the answer of #flex_elektro_deimling
First parameter UIView.animateWithDuration is the total time of the animation (In my case I've set it to 0.5), you may set different values on the first and second (delay) to change the blinking speed.
self.YOURLABEL.alpha = 0;
UIView.animateWithDuration(
0.5,
delay: 0.2,
options: UIViewAnimationOptions.Repeat | UIViewAnimationOptions.Autoreverse, animations: {
self.YOURLABEL.alpha = 1
},
completion:nil)
int count;
NSTimer *timer;
timer= [NSTimer
scheduledTimerWithTimeInterval:(NSTimeInterval)(0.5)
target:self
selector:#selector(animationStart)
userInfo:nil
repeats:TRUE];
-(void)animationStart{
switch (count) {
case 0:
//205 198 115
count++;
lbl.textColor=[UIColor colorWithRed:205.0f/255.0f green:198.0f/255.0f blue:115.0f/255.0f alpha:1];
break;
case 1:
count++;
//205 198 115 56 142 142
lbl.textColor=[UIColor colorWithRed:56.0f/255.0f green:142.0f/255.0f blue:142.0f/255.0f alpha:1];
break;
case 2:
count++;
//205 198 115
lbl.textColor=[UIColor colorWithRed:205.0f/255.0f green:205.0f/255.0f blue:0.0f/255.0f alpha:1];
break;
case 3:
count++;
//205 198 115 84 255 159
lbl.textColor=[UIColor colorWithRed:84.0f/255.0f green:255.0f/255.0f blue:159.0f/255.0f alpha:1];
break;
case 4:
count++;
//205 198 115 255 193 37
lbl.textColor=[UIColor colorWithRed:255.0f/255.0f green:193.0f/255.0f blue:37.0f/255.0f alpha:1];
break;
case 5:
count++;
//205 198 115 205 200 177
lbl.textColor=[UIColor colorWithRed:205.0f/255.0f green:200.0f/255.0f blue:117.0f/255.0f alpha:1];
break;
case 6:
count++;
//205 198 115 255 228 181
lbl.textColor=[UIColor colorWithRed:255.0f/255.0f green:228.0f/255.0f blue:181.0f/255.0f alpha:1];
break;
case 7:
count++;
//205 198 115 233 150 122
lbl.textColor=[UIColor colorWithRed:233.0f/255.0f green:150.0f/255.0f blue:122.0f/255.0f alpha:1];
break;
case 8:
count++;
//205 198 115 233 150 122
lbl.textColor=[UIColor colorWithRed:255.0f/255.0f green:200.0f/255.0f blue:200.0f/255.0f alpha:1];
break;
case 9:
count=0;
//205 198 115 255 99 71 255 48 48
lbl.textColor=[UIColor colorWithRed:255.0f/255.0f green:48.0f/255.0f blue:48.0f/255.0f alpha:1];
break;
default:
break;
}
}
Here is my solution in Swift 4.0 with extension for any UIVIew
extension UIView{
func blink() {
self.alpha = 0.2
UIView.animate(withDuration: 1,
delay: 0.0,
options: [.curveLinear,
.repeat,
.autoreverse],
animations: { self.alpha = 1.0 },
completion: nil)
}
}
For Swift 3+, building on all the great answers here, I ended up with a few tweaks that gave me smooth blinking effect that automatically stops after a given number of cycles.
extension UIView {
func blink(duration: Double=0.5, repeatCount: Int=2) {
self.alpha = 0.0;
UIView.animate(withDuration: duration,
delay: 0.0,
options: [.curveEaseInOut, .autoreverse, .repeat],
animations: { [weak self] in
UIView.setAnimationRepeatCount(Float(repeatCount) + 0.5)
self?.alpha = 1.0
}
)
}
}
Related
I have UIButton, that i wish to rotate in one direction for 180 degrees, and back also for 180 degrees. I have been doing animations for a while using CABasicAnimation, but this time i wanted to do it with transforms. Here is the code that i have written:
- (IBAction)blurAction:(id)sender {
if (self.blurActive) {
[UIView animateWithDuration:0.1 animations:^{
self.blurView.alpha = 0;
self.blurButton.transform = CGAffineTransformMakeRotation(M_PI);
} completion:^(BOOL finished) {
self.blurActive = NO;
}];
}
else {
[UIView animateWithDuration:0.1 animations:^{
self.blurView.alpha = 1;
self.blurButton.transform = CGAffineTransformMakeRotation(-M_PI);
} completion:^(BOOL finished) {
self.blurActive = YES;
}];
}
}
It works the first time, but second time i press the button, nothing happens. Can someone explain what I am doing wrong here?
The easiest way to achieve this effect is just to rotate a tiny, tiny amount less than 180°:
- (IBAction)toggle:(UIButton *)sender {
[UIView animateWithDuration:0.2 animations:^{
if (CGAffineTransformEqualToTransform(sender.transform, CGAffineTransformIdentity)) {
sender.transform = CGAffineTransformMakeRotation(M_PI * 0.999);
} else {
sender.transform = CGAffineTransformIdentity;
}
}];
}
Result:
Here is the Swift3 code for #rob mayoff solution.
#IBAction func fooButton(_ sender: Any) {
UIView.animate(withDuration:0.1, animations: { () -> Void in
if sender.transform == .identity {
sender.transform = CGAffineTransform(rotationAngle: CGFloat(M_PI * 0.999))
} else {
sender.transform = .identity
}
})
}
Swift4
M_PI is deprecated and replaced with Double.pi
#IBAction func fooButton(_ sender: Any) {
UIView.animate(withDuration:0.1, animations: { () -> Void in
if sender.transform == .identity {
sender.transform = CGAffineTransform(rotationAngle: CGFloat(Double.pi * 0.999))
} else {
sender.transform = .identity
}
})
}
M_PI and -M_PI will have the same visual effect
The turning back to it's original position should be
self.blurButton.transform = CGAffineTransformMakeRotation(0);
--EDIT--
To animate the counter clockwise rotation, you can use -2*M_PI
self.blurButton.transform = CGAffineTransformMakeRotation(-2*M_PI);
Turning UIButton 180º
UIButton.transform = CGAffineTransform(rotationAngle: CGFloat(Double.pi))
Turning UIButton 0º or back again
UIButton.transform = CGAffineTransform(rotationAngle: 0)
Example to turn animate
if cardViewModel.getBottomMenuVisibility() {
[UIView .transition(
with: bottomMenuView,
duration: 0.3,
options: .transitionCrossDissolve,
animations: {
// Turn UIButton upside down
self.bottomMenu.transform = CGAffineTransform(rotationAngle: CGFloat(Double.pi))
},
completion: nil)]
}
else {
[UIView .transition(
with: bottomMenuView,
duration: 0.3,
options: .transitionCrossDissolve,
animations: {
// Turn UIButton back to normal
self.bottomMenu.transform = CGAffineTransform(rotationAngle: 0)
},
completion: nil)]
}
You can check on my code this example :
https://github.com/issuran/Scrum-Geek-Poker/blob/0d032a4b4edcf75cebae1524131f4fe6be3a5edf/Scrum%20Geek%20Poker/Features/CardCollection/View/MainScreenViewController.swift
To 'unrotate' the view set the transform to the constant CGAffineTransformIdentity , which is a transform of zero. This is the beauty of working with transforms, you don't need to calculate the way back, just undo what you already did.
You can not actually achieve this with transforms as transforms holds only information about end state. They do not tell us which direction we should use to make e.g. the rotation.
The best option to achieve 180 degrees forth and back rotation behaviour is to use CABasicAnimation.
Here's the example:
func rotateImage(forward: Bool) {
let rotationAnimation = CABasicAnimation(keyPath: "transform.rotation.z")
rotationAnimation.fromValue = forward ? 0.0 : CGFloat.pi
rotationAnimation.toValue = forward ? CGFloat.pi : 0.0
rotationAnimation.fillMode = kCAFillModeForwards
rotationAnimation.isRemovedOnCompletion = false
rotationAnimation.duration = 0.5
handleImageView.layer.add(rotationAnimation, forKey: "rotationAnimation")
}
Swift 4+
#IBAction private func maximizeButtonAction(_ sender: UIButton) {
UIView.animate(withDuration: 0.2, animations: {
sender.transform = sender.transform == .identity ? CGAffineTransform(rotationAngle: CGFloat(Double.pi * 0.999)) : .identity
})
}
I am trying to change a button's color (just a flash/blink) to green when a scan is correct and red when there's a problem. I am able to do this with a view like so
func flashBG(){
UIView.animateWithDuration(0.7, animations: {
self.view.backgroundColor = UIColor.greenColor()
})
}
But with a button it stays green
func flashBtn(){
UIButton.animateWithDuration(0.5, animations: {
self.buttonScan.backgroundColor = UIColor.greenColor()
})
}
I have created the button by code
func setupScanButton() {
let X_Co = (self.view.frame.size.width - 100)/2
let Y_Co = (self.viewForLayer.frame.size.height + 36/2)
buttonScan.frame = CGRectMake(X_Co,Y_Co,100,100)
buttonScan.layer.borderColor = UIColor.whiteColor().CGColor
buttonScan.layer.borderWidth = 2
buttonScan.layer.cornerRadius = 50
buttonScan.setTitle("Scan", forState: .Normal)
buttonScan.backgroundColor = UIColor.blueColor()
buttonScan.addTarget(self, action: "buttonScanAction", forControlEvents: .TouchUpInside)
buttonScan.setTitleColor(UIColor(red:255/255, green: 255/255, blue:255/255, alpha: 1), forState: UIControlState.Normal)
self.view.addSubview(buttonScan)
}
Should i call setupScanButton() again?
This should work in Swift 4
extension UIView{
func blink() {
self.alpha = 0.2
UIView.animate(withDuration: 1, delay: 0.0, options: [.curveLinear, .repeat, .autoreverse], animations: {self.alpha = 1.0}, completion: nil)
}
}
This will start and stop a flashing button onClick, if you only want to flash the button immediately just use the first statement.
var flashing = false
#IBAction func btnFlash_Clicked(sender: AnyObject) {
if !flashing{
self.buttonScan.alpha = 1.0
UIView.animateWithDuration(0.5, delay: 0.0, options: [.CurveEaseInOut, .Repeat, .Autoreverse, .AllowUserInteraction], animations: {() -> Void in
self.buttonScan.alpha = 0.0
}, completion: {(finished: Bool) -> Void in
})
flashing = true
}
else{
UIView.animateWithDuration(0.1, delay: 0.0, options: [.CurveEaseInOut, .BeginFromCurrentState], animations: {() -> Void in
self.buttonScan.alpha = 1.0
}, completion: {(finished: Bool) -> Void in
})
}
}
Swift 5.x version
An updated version with extension.
extension UIView {
func blink(duration: TimeInterval = 0.5, delay: TimeInterval = 0.0, alpha: CGFloat = 0.0) {
UIView.animate(withDuration: duration, delay: delay, options: [.curveEaseInOut, .repeat, .autoreverse], animations: {
self.alpha = alpha
})
}
}
To call the function:
button.blink() // without parameters
button.blink(duration: 1, delay: 0.1, alpha: 0.2) // with parameters
I hope that will solve your problem.
buttonScan.alpha = 1.0
UIView.animate(withDuration: 1.0, delay: 1.0, options: UIView.AnimationOptions.curveEaseOut, animations: {
buttonScan.alpha = 0.0
}, completion: nil)
Swift 4:
I've maked an extension with some useful options:
extension UIButton {
open override func hitTest(_ point: CGPoint, with event: UIEvent?) -> UIView? {
return self.bounds.contains(point) ? self : nil
}
func blink(enabled: Bool = true, duration: CFTimeInterval = 1.0, stopAfter: CFTimeInterval = 0.0 ) {
enabled ? (UIView.animate(withDuration: duration, //Time duration you want,
delay: 0.0,
options: [.curveEaseInOut, .autoreverse, .repeat],
animations: { [weak self] in self?.alpha = 0.0 },
completion: { [weak self] _ in self?.alpha = 1.0 })) : self.layer.removeAllAnimations()
if !stopAfter.isEqual(to: 0.0) && enabled {
DispatchQueue.main.asyncAfter(deadline: .now() + stopAfter) { [weak self] in
self?.layer.removeAllAnimations()
}
}
}
}
First of all, I've overrided the hittest function to enabling the touch also when the button have the alpha equals to 0.0 (transparent) during the animation.
Then , all input vars have a default value so you can launch the blink() method without parameters
I've introduced also the enabled parameter to start or stop the animations on your button.
Finally, if you want you can stop animation after a specific time with the stopAfter parameter.
Usage:
yourButton.blink() // infinite blink effect with the default duration of 1 second
yourButton.blink(enabled:false) // stop the animation
yourButton.blink(duration: 2.0) // slowly the animation to 2 seconds
yourButton.blink(stopAfter:5.0) // the animation stops after 5 seconds.
Typical uses:
yourButton.blink(duration: 1.5, stopAfter:10.0)
// your code..
yourButton.blink()
// other code..
yourButton.blink(enabled:false)
You can try something like this:
extension UIView {
func blink() {
UIView.animateWithDuration(0.5, //Time duration you want,
delay: 0.0,
options: [.CurveEaseInOut, .Autoreverse, .Repeat],
animations: { [weak self] in self?.alpha = 0.0 },
completion: { [weak self] _ in self?.alpha = 1.0 })
dispatch_after(dispatch_time(DISPATCH_TIME_NOW,Int64(2 * NSEC_PER_SEC)),dispatch_get_main_queue()){
[weak self] in
self?.layer.removeAllAnimations()
}
}
}
//MARK : Usage
yourButton.flash()
extension UIButton {
func flash() {
let flash = CABasicAnimation(keyPath: "opacity")
flash.duration = 0.5
flash.fromValue = 1
flash.toValue = 0.1
flash.timingFunction = CAMediaTimingFunction(name: CAMediaTimingFunctionName.easeInEaseOut)
flash.autoreverses = true
flash.repeatCount = 3
layer.add(flash, forKey: nil)
}
}
Swift 3.0
func btnFlash_Clicked(sender: AnyObject) {
if !flashing{
callButton.alpha = 1.0
UIView.animate(withDuration: 0.5, delay: 0.0, options: [.allowUserInteraction], animations: {() -> Void in
callButton.alpha = 0.5
}, completion: {(finished: Bool) -> Void in
})
flashing = true
}
else{
flashing = false
callButton.alpha = 0.5
UIView.animate(withDuration: 0.5, delay: 0.0, options: [.allowUserInteraction], animations: {() -> Void in
callButton.alpha = 1.0
}, completion: {(finished: Bool) -> Void in
})
}
}
with UIViewPropertyAnimator and Swift 5
UIViewPropertyAnimator.runningPropertyAnimator(withDuration: 1, delay: 0, options: [.curveLinear,.repeat], animations: {
UIView.setAnimationRepeatCount(3000)
self.buttonScan.alpha = 0.0
}, completion: {_ in })
Swift 3.0
func animateFlash() {
flashView.alpha = 0
flashView.isHidden = false
UIView.animate(withDuration: 0.3, animations: { flashView.alpha = 1.0 }) { finished in flashView.isHidden = true }
}
This UIView extension "blinks" a view and changes the background colour:
/**
Blinks a view with a given duration and optional color.
- Parameter duration: The duration of the blink.
- Parameter color: The color of the blink.
*/
public func blink(withDuration duration: Double = 0.25, color: UIColor? = nil) {
alpha = 0.2
UIView.animate(withDuration: duration, delay: 0.0, options: [.curveEaseInOut], animations: {
self.alpha = 1.0
})
guard let newBackgroundColor = color else { return }
let oldBackgroundColor = backgroundColor
UIView.animate(withDuration: duration, delay: 0.0, options: [.curveEaseInOut], animations: {
self.backgroundColor = newBackgroundColor
self.backgroundColor = oldBackgroundColor
})
}
You would then use as follows:
buttonScan.blink(color: .green)
myButton.alpha = 0.7
UIView.animate(withDuration: 0.3,
delay: 1.0,
options: [UIView.AnimationOptions.curveLinear, UIView.AnimationOptions.repeat, UIView.AnimationOptions.autoreverse],
animations: { myButton.alpha = 1.0 },
completion: nil)
Another smoothly animating version for Swift 5:
public extension UIView {
func blink(duration: TimeInterval) {
let initialAlpha: CGFloat = 1
let finalAlpha: CGFloat = 0.2
alpha = initialAlpha
UIView.animateKeyframes(withDuration: duration, delay: 0, options: .beginFromCurrentState) {
UIView.addKeyframe(withRelativeStartTime: 0, relativeDuration: 0.5) {
self.alpha = finalAlpha
}
UIView.addKeyframe(withRelativeStartTime: 0.5, relativeDuration: 0.5) {
self.alpha = initialAlpha
}
}
}
}
I have a UIViewController which has UITableView and on to the UITableView I am animating a UIView when the button is selected in the tableview cell. In the UIView I have a UITextField, now when I click in the textfield the UIView disappears.
I am doing this in Swift 2.0. Any suggestions about this issue and if possible with some explanation/sample code reference.
Below is the animation process I am doing when the button is selected in UITableViewCell
if !cell.btnBuy.selected
{
UIView.animateWithDuration(0.5, delay: 0.1, options: UIViewAnimationOptions.CurveEaseIn, animations: {
self.buyView.frame = CGRectMake(0.0, self.buyView.frame.origin.y - (56.0 + 64.0 + 43.0 + self.SearchBar.frame.origin.y + self.Segment.frame.origin.y), self.view.frame.size.width, 412.0)
}) { (finished) -> Void in}
UIView.commitAnimations()
}
Thanks.
dispatch_async(dispatch_get_main_queue, ^{
UIView.animateWithDuration(0.5, delay: 0.1, options: UIViewAnimationOptions.CurveEaseIn, animations: {
self.buyView.frame = CGRectMake(0.0, self.buyView.frame.origin.y - (56.0 + 64.0 + 43.0 + self.SearchBar.frame.origin.y + self.Segment.frame.origin.y), self.view.frame.size.width, 412.0)
}) { (finished) -> Void in}
UIView.commitAnimations()
});
I am trying to have a UIView animate as a floating object, or as a Balloon :D
The UIView is in the middle of the screen, and I want it to keep floating randomly around its first initiated spot. Not across the screen or anything like that, just floating in the area of 5 pixels around it.
Any suggestions? :D
I tried this:
[UIView animateWithDuration:0.1
delay:0.0
options: UIViewAnimationOptionRepeat | UIViewAnimationOptionAutoreverse | UIViewAnimationOptionAllowUserInteraction
animations:^{
myCircleUIView.transform = CGAffineTransformMakeTranslation([self randomFloatingGenerator], [self randomFloatingGenerator]);
}
completion:NULL];
randomFloatingGenerator generates a number between -5 and 5. Problem is, it only executes once, and keeps repeating with the same random values.
EDIT1:
Now I have tried This
-(void)animationLoop{
[UIView animateWithDuration:1.0
animations: ^{ myCircleUIView.transform = CGAffineTransformMakeTranslation([self randomFloatingGenerator], [self randomFloatingGenerator]); }
completion:
^(BOOL finished) {
[UIView animateWithDuration:1.0
animations:^{ myCircleUIView.transform = CGAffineTransformMakeTranslation(0,0);
}
completion:
^(BOOL finished) {[self animationLoop];}];
}];
But it is still not working, the animation is.... Cracky... I think I am doing some stupid mistake that I need a second set of eyes to help me with.
EDIT2:
Fixed it.
-(void)animationLoop{
CGPoint oldPoint = CGPointMake(myCircleUIView.frame.origin.x, myCircleUIView.frame.origin.y);
[UIView animateWithDuration:1.0
animations: ^{ myCircleUIView.frame = CGRectMake(myCircleUIView.frame.origin.x + [self randomFloatingGenerator], myCircleUIView.frame.origin.y + [self randomFloatingGenerator], myCircleUIView.frame.size.width, myCircleUIView.frame.size.height); }
completion:
^(BOOL finished) {
[UIView animateWithDuration:1.0
animations:^{ myCircleUIView.frame = CGRectMake(oldPoint.x, oldPoint.y, myCircleUIView.frame.size.width, myCircleUIView.frame.size.height);}
completion:
^(BOOL finished) {[self animationLoop];}];
}];
}
Thanks for the help anyone.
EDIT 3:
Someone posted an enhanced code.
#Shamy's solution, improved, fixed and CPU safe.
-(void)animateFloatView:(UIView*)view{
// Abort the recursive loop
if (!view)
return;
CGPoint oldPoint = CGPointMake(view.frame.origin.x, view.frame.origin.y);
[UIView animateWithDuration:0.6
animations: ^{ view.frame = CGRectMake(view.frame.origin.x, view.frame.origin.y - 15, view.frame.size.width, view.frame.size.height); }
completion:
^(BOOL finished) {
if (finished) {
[UIView animateWithDuration:0.6
animations:^{ view.frame = CGRectMake(oldPoint.x, oldPoint.y, view.frame.size.width, view.frame.size.height);}
completion:
^(BOOL finished2) {
if(finished2)
[self animateFloatView:view];
}];
}
}];
}
Whenever you want to stop the animation (necessary when leaving the View Controller), call the function using nil, as this:
[self recursiveFloatingAnimation:nil];
Not stoping the animation will cause the recursive loop to run infinitely and overwhelm the CPU stack.
Swift 4
UIView.animate(withDuration: 0.6, delay: 0.1, options: [.autoreverse, .repeat], animations: {
self.frame = CGRect(x: self.frame.origin.x, y: self.frame.origin.y - 15, width: self.frame.size.width, height: self.frame.size.height)
},completion: nil )
It will behave in that way. As you are repeating the animation not the function. So it will repeat same animation every time you set at first call. Do it like:
#interface AAViewController ()
#property (nonatomic, strong) UIView * floatingView;
#end
#implementation AAViewController
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
_floatingView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 50, 50)];
[_floatingView setBackgroundColor:[UIColor redColor]];
[self.view addSubview:_floatingView];
[self circleUIViewFloating];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#pragma mark - Circle UIView floating
- (void) circleUIViewFloating {
[UIView animateWithDuration:2.0
animations:^{
_floatingView.transform = CGAffineTransformMakeTranslation([self randomFloatingGenerator : 270], [self randomFloatingGenerator:480]);
} completion:^(BOOL finished) {
[self circleUIViewFloating];
}];
}
- (int) randomFloatingGenerator : (int) max{
return arc4random() % max;
}
Here is complete running project for this.
You can achieve the hovering or floating effect using CABasicAnimation.
You will have to include the QuartzCore framework to use this.
Swift 4.2:
import QuartzCore
let hover = CABasicAnimation(keyPath: "position")
hover.isAdditive = true
hover.fromValue = NSValue(cgPoint: CGPoint.zero)
hover.toValue = NSValue(cgPoint: CGPoint(x: 0.0, y: -5.0))
hover.autoreverses = true
hover.duration = 0.8
hover.repeatCount = Float.infinity
myCustomView.layer.add(hover, forKey: "hoverAnimation")
Make sure to remove the animation when the view is no longer being shown.
override func viewWillDisappear(_ animated: Bool) {
// Stop animating when view is going to disappear
myCustomView.layer.removeAllAnimations()
}
-(void)animationLoop{
CGPoint oldPoint = CGPointMake(myCircleUIView.frame.origin.x, myCircleUIView.frame.origin.y);
[UIView animateWithDuration:1.0
animations: ^{ myCircleUIView.frame = CGRectMake(myCircleUIView.frame.origin.x + [self randomFloatingGenerator], myCircleUIView.frame.origin.y + [self randomFloatingGenerator], myCircleUIView.frame.size.width, myCircleUIView.frame.size.height); }
completion:
^(BOOL finished) {
[UIView animateWithDuration:1.0
animations:^{ myCircleUIView.frame = CGRectMake(oldPoint.x, oldPoint.y, myCircleUIView.frame.size.width, myCircleUIView.frame.size.height);}
completion:
^(BOOL finished) {[self animationLoop];}];
}];
}
Swift 2.1 Version Here:
func animateFloatView(view: UIView?) {
// Abort the recursive loop
guard let view = view else { return }
let oldPoint: CGPoint = CGPointMake(view.frame.origin.x, view.frame.origin.y)
UIView.animateWithDuration(0.6, animations: {() -> Void in
view.frame = CGRectMake(view.frame.origin.x, view.frame.origin.y - 15, view.frame.size.width, view.frame.size.height)
}, completion: {(finished: Bool) -> Void in
if finished {
UIView.animateWithDuration(0.6, animations: {() -> Void in
view.frame = CGRectMake(oldPoint.x, oldPoint.y, view.frame.size.width, view.frame.size.height)
}, completion: {(finished2: Bool) -> Void in
if finished2 {
self.animateFloatView(view)
}
})
}
})
}
Swift 3.1:
func animateFloatView(_ view: UIView?) {
guard let view = view else { return }
let oldYCoordinate = view.center.y
UIView.animate(withDuration: 0.6, animations: {
view.center.y -= 15
}, completion: { _ in
UIView.animate(withDuration: 0.6, animations: {
view.center.y = oldYCoordinate
}, completion: { _ in
self.animateFloatView(view)
})
})
}
My simple goal is to fade animate hiding and showing functions.
Button.hidden = YES;
Simple enough. However, is it possible to have it fade out rather than just disappearing? It looks rather unprofessional that way.
In iOS 4 and later, there's a way to do this just using the UIView transition method without needing to import QuartzCore. You can just say:
Objective C
[UIView transitionWithView:button
duration:0.4
options:UIViewAnimationOptionTransitionCrossDissolve
animations:^{
button.hidden = YES;
}
completion:NULL];
Swift
UIView.transition(with: button, duration: 0.4,
options: .transitionCrossDissolve,
animations: {
self.button.isHidden = false
})
Previous Solution
Michail's solution will work, but it's not actually the best approach.
The problem with alpha fading is that sometimes the different overlapping view layers look weird as they fade out. There are some other alternatives using Core Animation. First include the QuartzCore framework in your app and add #import <QuartzCore/QuartzCore.h> to your header. Now you can do one of the following:
set button.layer.shouldRasterize = YES; and then use the alpha animation code that Michail provided in his answer. This will prevent the layers from blending weirdly, but has a slight performance penalty, and can make the button look blurry if it's not aligned exactly on a pixel boundary.
Alternatively:
Use the following code to animate the fade instead:
CATransition *animation = [CATransition animation];
animation.type = kCATransitionFade;
animation.duration = 0.4;
[button.layer addAnimation:animation forKey:nil];
button.hidden = YES;
The nice thing about this approach is you can crossfade any property of the button even if they aren't animatable (e.g. the text or image of the button), just set up the transition and then set your properties immediately afterwards.
UIView animated properties are:
- frame
- bounds
- center
- transform
- alpha
- backgroundColor
- contentStretch
Describe in:
Animations
isHidden is not one of them, so as I see it the best way is:
Swift 4:
func setView(view: UIView, hidden: Bool) {
UIView.transition(with: view, duration: 0.5, options: .transitionCrossDissolve, animations: {
view.isHidden = hidden
})
}
Objective C:
- (void)setView:(UIView*)view hidden:(BOOL)hidden {
[UIView transitionWithView:view duration:0.5 options:UIViewAnimationOptionTransitionCrossDissolve animations:^(void){
[view setHidden:hidden];
} completion:nil];
}
To fade out:
Objective-C
[UIView animateWithDuration:0.3 animations:^{
button.alpha = 0;
} completion: ^(BOOL finished) {//creates a variable (BOOL) called "finished" that is set to *YES* when animation IS completed.
button.hidden = finished;//if animation is finished ("finished" == *YES*), then hidden = "finished" ... (aka hidden = *YES*)
}];
Swift 2
UIView.animateWithDuration(0.3, animations: {
button.alpha = 0
}) { (finished) in
button.hidden = finished
}
Swift 3, 4, 5
UIView.animate(withDuration: 0.3, animations: {
button.alpha = 0
}) { (finished) in
button.isHidden = finished
}
To fade in:
Objective-C
button.alpha = 0;
button.hidden = NO;
[UIView animateWithDuration:0.3 animations:^{
button.alpha = 1;
}];
Swift 2
button.alpha = 0
button.hidden = false
UIView.animateWithDuration(0.3) {
button.alpha = 1
}
Swift 3, 4, 5
button.alpha = 0
button.isHidden = false
UIView.animate(withDuration: 0.3) {
button.alpha = 1
}
I use this little Swift 3 extension:
extension UIView {
func fadeIn(duration: TimeInterval = 0.5,
delay: TimeInterval = 0.0,
completion: #escaping ((Bool) -> Void) = {(finished: Bool) -> Void in }) {
UIView.animate(withDuration: duration,
delay: delay,
options: UIViewAnimationOptions.curveEaseIn,
animations: {
self.alpha = 1.0
}, completion: completion)
}
func fadeOut(duration: TimeInterval = 0.5,
delay: TimeInterval = 0.0,
completion: #escaping (Bool) -> Void = {(finished: Bool) -> Void in }) {
UIView.animate(withDuration: duration,
delay: delay,
options: UIViewAnimationOptions.curveEaseIn,
animations: {
self.alpha = 0.0
}, completion: completion)
}
}
Use this solution for a smooth fadeOut and fadeIn effects
extension UIView {
func fadeIn(duration: TimeInterval = 0.5, delay: TimeInterval = 0.0, completion: #escaping ((Bool) -> Void) = {(finished: Bool) -> Void in }) {
self.alpha = 0.0
UIView.animate(withDuration: duration, delay: delay, options: UIView.AnimationOptions.curveEaseIn, animations: {
self.isHidden = false
self.alpha = 1.0
}, completion: completion)
}
func fadeOut(duration: TimeInterval = 0.5, delay: TimeInterval = 0.0, completion: #escaping (Bool) -> Void = {(finished: Bool) -> Void in }) {
self.alpha = 1.0
UIView.animate(withDuration: duration, delay: delay, options: UIView.AnimationOptions.curveEaseOut, animations: {
self.isHidden = true
self.alpha = 0.0
}, completion: completion)
}
}
usage is as like
uielement.fadeIn()
uielement.fadeOut()
Thanks
Swift 3
func appearView() {
self.myView.alpha = 0
self.myView.isHidden = false
UIView.animate(withDuration: 0.9, animations: {
self.myView.alpha = 1
}, completion: {
finished in
self.myView.isHidden = false
})
}
swift 4.2
with extension :
extension UIView {
func hideWithAnimation(hidden: Bool) {
UIView.transition(with: self, duration: 0.5, options: .transitionCrossDissolve, animations: {
self.isHidden = hidden
})
}
}
simple method:
func setView(view: UIView, hidden: Bool) {
UIView.transition(with: view, duration: 0.5, options: .transitionCrossDissolve, animations: {
view.isHidden = hidden
})
}
the code of #Umair Afzal working fine in swift 5 after some changes
extension UIView {
func fadeIn(duration: TimeInterval = 0.5, delay: TimeInterval = 0.0, completion: #escaping ((Bool) -> Void) = {(finished: Bool) -> Void in }) {
self.alpha = 0.0
UIView.animate(withDuration: duration, delay: delay, options: UIView.AnimationOptions.curveEaseIn, animations: {
self.isHidden = false
self.alpha = 1.0
}, completion: completion)
}
func fadeOut(duration: TimeInterval = 0.5, delay: TimeInterval = 0.0, completion: #escaping (Bool) -> Void = {(finished: Bool) -> Void in }) {
self.alpha = 1.0
UIView.animate(withDuration: duration, delay: delay, options: UIView.AnimationOptions.curveEaseIn, animations: {
self.alpha = 0.0
}) { (completed) in
self.isHidden = true
completion(true)
}
}
}
for use
yourView.fadeOut()
yourView.fadeIn()
I created category for UIView for this purpose and implemented a special little bit different concept: visibility. The main difference of my solution is that you can call [view setVisible:NO animated:YES] and right after that synchronously check [view visible] and get correct result. This is pretty simple but extremely useful.
Besides, it is allowed to avoid using "negative boolean logic" (see Code Complete, page 269, Use positive boolean variable names for more information).
Swift
UIView+Visibility.swift
import UIKit
private let UIViewVisibilityShowAnimationKey = "UIViewVisibilityShowAnimationKey"
private let UIViewVisibilityHideAnimationKey = "UIViewVisibilityHideAnimationKey"
private class UIViewAnimationDelegate: NSObject {
weak var view: UIView?
dynamic override func animationDidStop(animation: CAAnimation, finished: Bool) {
guard let view = self.view where finished else {
return
}
view.hidden = !view.visible
view.removeVisibilityAnimations()
}
}
extension UIView {
private func removeVisibilityAnimations() {
self.layer.removeAnimationForKey(UIViewVisibilityShowAnimationKey)
self.layer.removeAnimationForKey(UIViewVisibilityHideAnimationKey)
}
var visible: Bool {
get {
return !self.hidden && self.layer.animationForKey(UIViewVisibilityHideAnimationKey) == nil
}
set {
let visible = newValue
guard self.visible != visible else {
return
}
let animated = UIView.areAnimationsEnabled()
self.removeVisibilityAnimations()
guard animated else {
self.hidden = !visible
return
}
self.hidden = false
let delegate = UIViewAnimationDelegate()
delegate.view = self
let animation = CABasicAnimation(keyPath: "opacity")
animation.fromValue = visible ? 0.0 : 1.0
animation.toValue = visible ? 1.0 : 0.0
animation.fillMode = kCAFillModeForwards
animation.removedOnCompletion = false
animation.delegate = delegate
self.layer.addAnimation(animation, forKey: visible ? UIViewVisibilityShowAnimationKey : UIViewVisibilityHideAnimationKey)
}
}
func setVisible(visible: Bool, animated: Bool) {
let wereAnimationsEnabled = UIView.areAnimationsEnabled()
if wereAnimationsEnabled != animated {
UIView.setAnimationsEnabled(animated)
defer { UIView.setAnimationsEnabled(!animated) }
}
self.visible = visible
}
}
Objective-C
UIView+Visibility.h
#import <UIKit/UIKit.h>
#interface UIView (Visibility)
- (BOOL)visible;
- (void)setVisible:(BOOL)visible;
- (void)setVisible:(BOOL)visible animated:(BOOL)animated;
#end
UIView+Visibility.m
#import "UIView+Visibility.h"
NSString *const UIViewVisibilityAnimationKeyShow = #"UIViewVisibilityAnimationKeyShow";
NSString *const UIViewVisibilityAnimationKeyHide = #"UIViewVisibilityAnimationKeyHide";
#implementation UIView (Visibility)
- (BOOL)visible
{
if (self.hidden || [self.layer animationForKey:UIViewVisibilityAnimationKeyHide]) {
return NO;
}
return YES;
}
- (void)setVisible:(BOOL)visible
{
[self setVisible:visible animated:NO];
}
- (void)setVisible:(BOOL)visible animated:(BOOL)animated
{
if (self.visible == visible) {
return;
}
[self.layer removeAnimationForKey:UIViewVisibilityAnimationKeyShow];
[self.layer removeAnimationForKey:UIViewVisibilityAnimationKeyHide];
if (!animated) {
self.alpha = 1.f;
self.hidden = !visible;
return;
}
self.hidden = NO;
CGFloat fromAlpha = visible ? 0.f : 1.f;
CGFloat toAlpha = visible ? 1.f : 0.f;
NSString *animationKey = visible ? UIViewVisibilityAnimationKeyShow : UIViewVisibilityAnimationKeyHide;
CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:#"opacity"];
animation.duration = 0.25;
animation.fromValue = #(fromAlpha);
animation.toValue = #(toAlpha);
animation.delegate = self;
animation.removedOnCompletion = NO;
animation.fillMode = kCAFillModeForwards;
[self.layer addAnimation:animation forKey:animationKey];
}
#pragma mark - CAAnimationDelegate
- (void)animationDidStop:(CAAnimation *)animation finished:(BOOL)finished
{
if ([[self.layer animationForKey:UIViewVisibilityAnimationKeyHide] isEqual:animation]) {
self.hidden = YES;
}
}
#end
Swift 5.0, with generics:
func hideViewWithAnimation<T: UIView>(shouldHidden: Bool, objView: T) {
if shouldHidden == true {
UIView.animate(withDuration: 0.3, animations: {
objView.alpha = 0
}) { (finished) in
objView.isHidden = shouldHidden
}
} else {
objView.alpha = 0
objView.isHidden = shouldHidden
UIView.animate(withDuration: 0.3) {
objView.alpha = 1
}
}
}
Use:
hideViewWithAnimation(shouldHidden: shouldHidden, objView: itemCountLabelBGView)
hideViewWithAnimation(shouldHidden: shouldHidden, objView: itemCountLabel)
hideViewWithAnimation(shouldHidden: shouldHidden, objView: itemCountButton)
Here itemCountLabelBGView is a UIView, itemCountLabel is a UILabel & itemCountButton is a UIButton, So it will work for every view object whose parent class is UIView.
Swift 4
extension UIView {
func fadeIn(duration: TimeInterval = 0.5, delay: TimeInterval = 0.0, completion: #escaping ((Bool) -> Void) = {(finished: Bool) -> Void in }) {
self.alpha = 0.0
UIView.animate(withDuration: duration, delay: delay, options: UIViewAnimationOptions.curveEaseIn, animations: {
self.isHidden = false
self.alpha = 1.0
}, completion: completion)
}
func fadeOut(duration: TimeInterval = 0.5, delay: TimeInterval = 0.0, completion: #escaping (Bool) -> Void = {(finished: Bool) -> Void in }) {
self.alpha = 1.0
UIView.animate(withDuration: duration, delay: delay, options: UIViewAnimationOptions.curveEaseIn, animations: {
self.alpha = 0.0
}) { (completed) in
self.isHidden = true
completion(true)
}
}
}
And to use use it, simple call these functions like:
yourView.fadeOut() // this will hide your view with animation
yourView.fadeIn() /// this will show your view with animation
isHidden is an immediate value and you cannot affect an animation on it, instead of this you can use Alpha for hide your view
UIView.transition(with: view, duration: 0.5, options: .transitionCrossDissolve, animations: {
view.alpha = 0
})
And for showing:
UIView.transition(with: view, duration: 0.5, options: .transitionCrossDissolve, animations: {
view.alpha = 1
})
func flipViews(fromView: UIView, toView: UIView) {
toView.frame.origin.y = 0
self.view.isUserInteractionEnabled = false
UIView.transition(from: fromView, to: toView, duration: 0.5, options: .transitionFlipFromLeft, completion: { finished in
fromView.frame.origin.y = -900
self.view.isUserInteractionEnabled = true
})
}
You can try this.
func showView(objView:UIView){
objView.alpha = 0.0
UIView.animate(withDuration: 0.5, animations: {
objView.alpha = 0.0
}, completion: { (completeFadein: Bool) -> Void in
objView.alpha = 1.0
let transition = CATransition()
transition.duration = 0.5
transition.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut)
transition.type = kCATransitionFade
objView.layer.add(transition, forKey: nil)
})
}
func HideView(objView:UIView){
UIView.animate(withDuration: 0.5, animations: {
objView.alpha = 1.0
}, completion: { (completeFadein: Bool) -> Void in
objView.alpha = 0.0
let transition = CATransition()
transition.duration = 0.5
transition.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut)
transition.type = kCATransitionFade
objView.layer.add(transition, forKey: nil)
})
}
And pass your view name
showView(objView: self.viewSaveCard)
HideView(objView: self.viewSaveCard)
If your view is set to hidden by default or you change the Hidden state which I think you should in many cases, then none of the approaches in this page will give you both FadeIn/FadeOut animation, it will only animate one of these states, the reason is you are setting the Hidden state to false before calling UIView.animate method which will cause a sudden visibility and if you only animate the alpha then the object space is still there but it's not visible which will result to some UI issues.
So the best approach is to check first if the view is hidden then set the alpha to 0.0, like this when you set the Hidden state to false you won't see a sudden visibility.
func hideViewWithFade(_ view: UIView) {
if view.isHidden {
view.alpha = 0.0
}
view.isHidden = false
UIView.animate(withDuration: 0.3, delay: 0.0, options: .transitionCrossDissolve, animations: {
view.alpha = view.alpha == 1.0 ? 0.0 : 1.0
}, completion: { _ in
view.isHidden = !Bool(truncating: view.alpha as NSNumber)
})
}
UIView.transition(with:) function is nice and neat.
Many have posted it but none has noticed there lies a fault will show up only when you run it.
You can transition hidden property to true perfectly, whereas when you attempt to transition it to false, the view will simple disappear suddenly without any animation.
That's because this api only works within a view, which means when you transition a view to show, in fact itself shows immediately, only its content animated out gradually.
When you try to hide this view, itself hide right away, makes the animation to its content meaningless.
To solve this, when hiding a view, the transition target should be its parent view instead of the view you want to hide.
func transitionView(_ view: UIView?, show: Bool, completion: BoolFunc? = nil) {
guard let view = view, view.isHidden == show, let parent = view.superview else { return }
let target: UIView = show ? view : parent
UIView.transition(with: target, duration: 0.4, options: [.transitionCrossDissolve], animations: {
view.isHidden = !show
}, completion: completion)
}
UIView.transition(with: title3Label, duration: 0.4,
options: .transitionCrossDissolve,
animations: {
self.title3Label.isHidden = !self.title3Label.isHidden
})
Applying transition on View with some delay gives hide and show effect
You can do it VERY easily using Animatics library:
//To hide button:
AlphaAnimator(0) ~> button
//to show button
AlphaAnimator(1) ~> button
My solution for Swift 3. So, I created the function, that hide/unhide view in the right order(when hiding - set alpha to 0 and then isHidden to true; unhiding - first reveal the view and then set it's alpha to 1):
func hide(_ hide: Bool) {
let animations = hide ? { self.alpha = 0 } :
{ self.isHidden = false }
let completion: (Bool) -> Void = hide ? { _ in self.isHidden = true } :
{ _ in UIView.animate(withDuration: duration, animations: { self.alpha = 1 }) }
UIView.animate(withDuration: duration, animations: animations, completion: completion)
}
Swift 4 Transition
UIView.transition(with: view, duration: 3, options: .transitionCurlDown,
animations: {
// Animations
view.isHidden = hidden
},
completion: { finished in
// Compeleted
})
If you use the approach for older swift versions you'll get an error :
Cannot convert value of type '(_) -> ()' to expected argument type '(() -> Void)?'
Useful reference.
This code give an animation like pushing viewController in
uinavigation controller...
CATransition *animation = [CATransition animation];
animation.type = kCATransitionPush;
animation.subtype = kCATransitionFromRight;
animation.duration = 0.3;
[_viewAccountName.layer addAnimation:animation forKey:nil];
_viewAccountName.hidden = true;
Used this for pop animation...
CATransition *animation = [CATransition animation];
animation.type = kCATransitionPush;
animation.subtype = kCATransitionFromLeft;
animation.duration = 0.3;
[_viewAccountName.layer addAnimation:animation forKey:nil];
_viewAccountName.hidden = false;
Tried some of the exited answers, some only work for one situation, some of them need to add two functions.
Option 1
Nothing to do with view.isHidden.
extension UIView {
func animate(fadeIn: Bool, withDuration: TimeInterval = 1.0) {
UIView.animate(withDuration: withDuration, delay: 0.0, options: .curveEaseInOut, animations: {
self.alpha = fadeIn ? 1.0 : 0.0
})
}
}
Then pass isFadeIn (true or false)
view.animate(fadeIn: isFadeIn)
Option 2
Don't pass any parameter. It fades in or out according to isUserInteractionEnabled. This also suits the situation animate back and forth very well.
func animateFadeInOut(withDuration: TimeInterval = 1.0) {
self.isUserInteractionEnabled = !self.isUserInteractionEnabled
UIView.animate(withDuration: withDuration, delay: 0.0, options: .curveEaseInOut, animations: {
self.alpha = self.isUserInteractionEnabled ? 1.0 : 0.0
})
}
Then you call
yourView.animateFadeInOut()
Why self.isUserInteractionEnabled ?
Tried to replace self.isUserInteractionEnabled by self.isHidden,
no luck at all.
That's it. Cost me sometime, hope it helps someone.