본문 바로가기

iOS

iOS - UIImageView를 활용한 Animation 구현

안녕하세요, 오늘은 UIImageView 를 활용하여 iOS에서 Animation 효과를 구현해 보고자 합니다. 

정적 매소드로 UIView의 animate 메소드나 transition animations를 주로 사용하는데요, UIKit은 UIImageView를 여러개 활용하여 애니메이션을 생성하는 API 역시 제공합니다. 오늘은 그 방법을 구현해 보겠습니다. 

 

일단 UIImageView 는 애니메이션 활용을 위해 아래와 같은 속성과 메소드들을 제공합니다. 

var animationImages: [UIImage]? 

var highlightedAnimationImages: [UIImage]? 

var animationDuration: TimeInterval

var animationRepeatCount: Int 

func startAnimating() - 애니메이션 시작 

func stopAnimating()  - 애니메이션 종료

var isAnimating: Bool { get } - 애니메이션이 동작 중인지 알려주는 속성.

 

아래와 같이 아이콘이미지가 애니메이션을 통해 변하다가 3초 후, 연결되는 아이콘으로 변경되는 것을 확인 할 수 있습니다. 

 

import UIKit

 

enum CastState {

    case connected

    case disconnected

}

class ViewController: UIViewController {

    private var castState = CastState.disconnected

    

    @IBOutlet weak var chromecastImageView: UIImageView!

    @IBOutlet weak var connectionButton: UIButton!

    

    override func viewDidLoad() {

        super.viewDidLoad()

        setupImageViewAnimation()

        // Do any additional setup after loading the view.

    }

    private func setupImageViewAnimation() {

        chromecastImageView.animationImages = [imageLiteral(resourceName: "cast0"),  imageLiteral(resourceName: "cast1"),  imageLiteral(resourceName: "cast_disconnected")]

        chromecastImageView.animationDuration = 1

    }

    @IBAction func onConnectButton(_ sender: Any) {

        switch castState {

        case .connected:

            disconnect()

        case .disconnected:

            connect()

            

        }

    }

    private func connect() {

        connectionButton.isEnabled = false

        chromecastImageView.startAnimating()

        // Simulates a connection with a delay of 3 seconds

        DispatchQueue.main.asyncAfter(deadline: .now() + 3) {

            self.chromecastImageView.stopAnimating()

            // enables the button to allow user interaction

            self.connectionButton.isEnabled = true

            // update UI

            self.toggleCastState()

        }

    }

    private func disconnect() {

        toggleCastState()

    }

    func toggleCastState()  {

        castState = castState == .connected ? .disconnected : .connected

        // updates button title

        let buttonTitle = castState == .connected ? "Disconnected" : "Connected"

        connectionButton.setTitle(buttonTitle, for: .normal)

        let image = castState == .connected ?  imageLiteral(resourceName: "cast_connected") :  imageLiteral(resourceName: "cast_disconnected")

        chromecastImageView.image = image

        }

}

 

 

출처: https://marcosantadev.com/make-uiimageview-animations/

'iOS' 카테고리의 다른 글

iOS - UINavigationController + UISearchController + UISearchBarDelegate  (0) 2020.08.10
iOS - Alamofire  (0) 2020.08.04
iOS - IBOutlet & IBAction  (0) 2020.07.16
iOS - TableView Dynamic Cell  (0) 2020.07.14
Source Control with Xcode  (0) 2020.07.09