[Swift] How to implement the fade-in / out function

Introduction

Since the fade-in / out function was implemented when creating a personal application, We will share the command.

Please take a look at the code on GitHub. -> https://github.com/onishi-app/FeedInOut

environment

・ Apple Swift version 5.3 ・ XCode version 12.3

Completed form

⚠︎ Fade in / out starts every 4 seconds. nC9RSKQZk5ihDQ0K6HQs1610263334-1610263350.gif

code

The completed form of the code is as follows.

As you can see in @IBOutlet weak var button: UIButton! Since I added an object to StoryBoard and linked it with the code Even if you copy the whole text, a compile error will occur.

ViewController.swift



import UIKit

class ViewController: UIViewController {

    @IBOutlet weak var button: UIButton!
    var timer = Timer()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        button.layer.cornerRadius = 15
        
        //timer implementation
        timer = Timer.scheduledTimer(withTimeInterval: 4.0, repeats: true, block: { (timer) in
            self.animateView(self.button)
        })
        
    }
    
    //Fade in / out method
    func animateView(_ viewAnimate: UIView) {
        UIView.animate(withDuration: 0.5, delay: 0, options: .curveEaseIn) {
            viewAnimate.alpha = 0
        } completion: { (_) in
            UIView.animate(withDuration: 0.5, delay: 0, options: .curveEaseIn) {
                viewAnimate.alpha = 1
            }
        }
    }
    
    //Processing when the button is pressed
    @IBAction func buttonAction(_ sender: Any) {
        print("The button was pressed.")
    }
}

How to call

With self.animateView (self.button) You are calling a fade-in / out method.

ViewController.swift



//timer implementation
timer = Timer.scheduledTimer(withTimeInterval: 4.0, repeats: true, block: { (timer) in
    self.animateView(self.button)
})

Code description

** ~ Fade in / out ~ **

Define a method animateView () for fading in and out. This time, we will use the animate () method implemented in UIKit's UIView class.

ViewController.swift



//Fade in / out method
func animateView(_ viewAnimate: UIView) {
    UIView.animate(withDuration: 0.5, delay: 0, options: .curveEaseIn) {
        viewAnimate.alpha = 0
    } completion: { (_) in
        UIView.animate(withDuration: 0.5, delay: 0, options: .curveEaseIn) {
            viewAnimate.alpha = 1
        }
    }
}

There are some animate () methods written in the UIView class, This time I would like to use the following method.

UIKit.UIView



open class func animate(withDuration duration: TimeInterval, delay: TimeInterval, options: UIView.AnimationOptions = [], animations: @escaping () -> Void, completion: ((Bool) -> Void)? = nil)

** First argument: withDuration duration: TimeInterval ** The value of withDuration passes the time it takes to process.

This time, processing takes 0.5 seconds like withDuration: 0.5,.

** Second argument: delay: TimeInterval ** For delay, pass the time to delay.

If 1 is passed for delay, it will be executed 1 second after the method is called. This time, delay processing is not implemented like delay: 0.

** Third argument: options: UIView.AnimationOptions = [] ** In options, the behavior when performing animation processing is specified.

There are many types of options, so I will introduce some of them.

behavior
repeat Repeat the animation indefinitely
autoreverse If you want to repeat, run the animation back and forth
curveEaseInOut Movement to loosen the beginning and end(Default)
curveEaseIn Movement to loosen the beginning
curveEaseOut Movement to loosen the end
curveLinear Constant velocity

There are many other things, so if you are interested, please check it out!

This time, like options: .curveEaseIn, The initial movement is a little slower.

** Fourth argument: animations: @escaping ()-> Void ** In animations, describe the process to be executed.

It is defined as a closure, so let's write it in the form of a closure.

This time, like viewAnimate.alpha = 0, The alpha (transparency) of the value passed as an argument is set to 0 over 0.5 seconds.

alpha = 0 means to make it transparent.

** Fifth argument: completion: ((Bool)-> Void)? = Nil ** In completion, describe the processing after the processing is completed.

This time, like UIView.animate (・ ・ ・), Animation processing is being executed again after processing.

The second animation process takes ** 0.5 seconds to set alpha (transparency) to 1 **. In other words, it is in the displayed state.

The second completion is not described because there is no processing to be performed.

** ~ Timer implementation ~ **

Next is the implementation of Timer.

Use the ** Timer class ** implemented in Foundation. The Timer class has features such as ** a function that can repeat processing in a certain period of time **.

ViewController.swift



var timer = Timer()

//timer implementation
timer = Timer.scheduledTimer(withTimeInterval: 4.0, repeats: true, block: { (timer) in
    self.animateView(self.button)
})

Timer.scheduledTimer (・ ・ ・) is an iterative process.

This time, it is described in viewDidLoad (), so The Timer starts when the screen is loaded.

** About the scheduledTimer () method **

** First argument: withTimeInterval ** This describes how many seconds the process will take place.

** Second argument: repeats ** This specifies whether to repeat the process.

** If true, iterate, if false, repeat only once. ** **

In this case, it is true, so the first time, 4 seconds after the timer is called, It repeats like the second time, 4 seconds after the first process is called.

There is a total fade-in / out time of 1 second, so There will be 3 seconds when no animation is done.

** Third argument: block ** Here, describe the process you want to perform. Since it is a closure, you need to add the self keyword to function calls and so on.

This time, like self.animateView (self.button) Fade in / out is repeated every 4 seconds.

Finally

This completes the implementation of the fade-in / out function.

However, there is currently one weakness. That's because ** the buttons don't respond during the animation. ** **

So I couldn't tap the button for 1 second during the animation ** You can only tap for 3 seconds from the fade-in to the next fade-out. ** **

Maybe there is a way to do it during the animation, I didn't understand what I looked at at a glance, so I'll add it as soon as I understand it.

For the time being, I changed the button to a view and implemented a transparent button of the same size on it, I'll try to tap that ...

I would appreciate it if you could let me know.

It's easy to implement, so please use it.

Thank you for watching until the end.

Recommended Posts

[Swift] How to implement the fade-in / out function
[Swift] How to implement the countdown function
[Swift] How to implement the LINE login function
[swift5] How to implement the Twitter share function
[Swift] How to implement the Twitter login function using Firebase UI ①
[Swift] How to implement the Twitter login function using Firebase UI ②
How to implement the breadcrumb function using gretel
[For beginners] How to implement the delete function
How to add the delete function
[Swift] I tried to implement the function of the vending machine
[Java] How to use the hasNext function
How to put out the error bundling
How to implement TextInputLayout with validation function
[Swift5] How to implement standby screen using'PKHUD'
[Processing × Java] How to use the function
[Swift5] How to implement animation using "lottie-ios"
[Behavior confirmed in December 2020] How to implement the alert display function
[Swift] How to link the app with Firebase
How to implement the email authentication function at the time of user registration
How to implement UICollectionView in Swift with code only
Rails learning How to implement search function using ActiveModel
[Swift] How to get the document ID of Firebase
How to add ActionText function
[Swift] How to use UserDefaults
[Ruby] How to comment out
[Rails] How to implement scraping
[Java] How to implement multithreading
I tried to implement the like function by asynchronous communication
How to transition from the [Swift5] app to the iPhone settings screen
How to implement infinite scrolling (page nate) in Swift TableView
How to use the link_to method
How to use the include? method
How to find the average angle
How to use the wrapper class
Try to implement iOS14 Widget function
[Swift] How to use SwiftLint (cocoapods)
[Swift] How to use Unwind segue
[Swift 5] Implement UI for review function
[Swift] How to send a notification
[Rails] How to implement star rating
[Swift] How to replace multiple strings
[Swift] How to dynamically change the height of the toolbar on the keyboard
How to create a registration / update function where the table crosses
[Swift] How to display when the quiz app answers correctly [Beginner]
[Swift5] How to get an array and the complement of arrays
I tried to implement the image preview function with Rails / jQuery
[Swift UI] How to get the startup status of the application [iOS]
[Rails] How to put a crown mark on the ranking function
How to use MinIO with the same function as S3 Use docker-compose
A story about using the CoreImage framework to erase stains with Swift and implement a blur erase function
[Swift] How to pass the Label value in the selected collectionViewCell to the destination TextField
[Swift] Copy the character string to the clipboard
Shorten the UUID to base64 in Swift.
How to implement search functionality in Rails
How to implement date calculation in Java
How to implement Kalman filter in Java
How to implement search function with rails (multiple columns are also supported)
How to return a value from Model to Controller using the [Swift5] protocol
[Java] How to use the File class
How to delete the wrong migration file
[Spring Boot] I investigated how to implement post-processing of the received request.