123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114 |
- //
- // ImagesAnimateScrollView.swift
- // ContactPoster
- //
- // Created by TSYH on 2024/3/4.
- //
- import UIKit
- class ImagesAnimateScrollView: UIView {
- enum `Direction` {
- case leftToRight
- case rightToLeft
- case topToBottom
- case bottomToTop
- }
-
- lazy var imageView1 = UIImageView()
- lazy var imageView2 = UIImageView()
-
- var animationImageName: String? {
- didSet {
- if let imageName = animationImageName,
- let image = UIImage(named: imageName) {
- imageView1.image = image
- imageView2.image = image
- imageView1.frame.size = image.size
- imageView2.frame.size = image.size
-
- imageView1.contentMode = .scaleAspectFill
- imageView2.contentMode = .scaleAspectFill
- }
- }
- }
-
- lazy var direction: `Direction` = .leftToRight
- lazy var margin: CGFloat = 16.0
-
- override init(frame: CGRect) {
- super.init(frame: frame)
- setupObser()
- }
-
- required init?(coder: NSCoder) {
- super.init(coder: coder)
- setupObser()
- }
-
- func setupObser() {
- clipsToBounds = true
- NotificationCenter.default.addObserver(self, selector: #selector(onAppActiveNotify(_:)), name: UIApplication.didBecomeActiveNotification, object: nil)
- }
-
- @objc func onAppActiveNotify(_ notify: Notification) {
- DispatchQueue.main.async {
- self.startAnimation()
- }
- }
-
- func setupSubviews() {
- if imageView1.superview == nil {
- addSubview(imageView1)
- addSubview(imageView2)
- switch direction {
- case .leftToRight:
- imageView1.x = width-imageView1.width
- imageView1.y = 0
- imageView2.y = 0
- imageView2.x = imageView1.x-imageView2.width-margin
- case .rightToLeft:
- imageView1.x = 0
- imageView1.y = 0
- imageView2.y = 0
- imageView2.x = imageView1.width+margin
- case .topToBottom:
- imageView1.x = 0
- imageView1.y = height-imageView1.height
- imageView2.x = 0
- imageView2.y = imageView1.y-imageView2.height-margin
- case .bottomToTop:
- imageView1.x = 0
- imageView1.y = 0
- imageView2.x = 0
- imageView2.y = imageView1.height+margin
- }
- }
- }
-
- func startAnimation() {
- setupSubviews()
-
- for iv in [imageView1, imageView2] {
- iv.layer.removeAllAnimations()
- }
-
- var moveAnim = CABasicAnimation(keyPath: "position.x")
- switch direction {
- case .leftToRight:
- moveAnim.byValue = imageView1.width
- case .rightToLeft:
- moveAnim.byValue = -imageView1.width
- case .topToBottom:
- moveAnim = CABasicAnimation(keyPath: "position.y")
- moveAnim.byValue = imageView1.height
- case .bottomToTop:
- moveAnim = CABasicAnimation(keyPath: "position.y")
- moveAnim.byValue = -imageView1.height
- }
- moveAnim.duration = 36
- moveAnim.repeatCount = .greatestFiniteMagnitude
- imageView1.layer.add(moveAnim, forKey: "move")
- imageView2.layer.add(moveAnim, forKey: "move")
- }
- }
|