iOS18适配指南

iOS18适配指南之UIUpdateLink

2024-08-03  本文已影响0人  YungFan

介绍

使用

import SwiftUI
import UIKit

class ViewController: UIViewController {
    lazy var imageView: UIImageView = {
        let imageView = UIImageView(image: UIImage(systemName: "sun.min.fill"))
        imageView.contentMode = .scaleAspectFit
        imageView.frame = .init(x: 100, y: 100, width: 64, height: 64)
        return imageView
    }()
    // UIUpdateLink
    var updateLink: UIUpdateLink!

    override func viewDidLoad() {
        super.viewDidLoad()

        // 关联UIView,当该UIView添加到父UIView或者UIWindows时自动激活,移除时自动失效
        updateLink = UIUpdateLink(view: imageView)
        // 添加Action,可以添加多个Action
        // 既可以使用Target-Action方式,也可以通过闭包方式
        updateLink.addAction(target: self, selector: #selector(update))
        updateLink.addAction { link, info in
        }
        // 添加到特定阶段
        updateLink.addAction(to: .afterUpdateComplete, target: self, selector: #selector(update))
        updateLink.addAction(to: .afterUpdateScheduled) { link, info in
            self.imageView.center.x = cos(info.modelTime) * 150 + self.view.bounds.midX
            print("闭包", link, info)
        }
        updateLink.isEnabled = true
        updateLink.requiresContinuousUpdates = true
        view.addSubview(imageView)
    }

    // MARK: UI更新时调用
    @objc func update(link: UIUpdateLink, info: UIUpdateInfo) {
        print("Target-Action", link, info)
        // info包含有关当前UI更新状态的详细信息
        imageView.center.y = sin(info.modelTime) * 300 + view.bounds.midY
    }

    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        imageView.removeFromSuperview()
    }
}
import UIKit

class ViewController: UIViewController {
    lazy var redView: UIView = {
        let redView = UIView(frame: CGRect(x: 0, y: 0, width: 200, height: 200))
        redView.backgroundColor = .red
        redView.alpha = 0
        redView.center = view.center
        return redView
    }()
    // UIUpdateLink
    var updateLink: UIUpdateLink!

    override func viewDidLoad() {
        super.viewDidLoad()

        view.addSubview(redView)
    }

    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        updateLink = UIUpdateLink(view: redView)
        updateLink.addAction { link, info in
            let layer = self.redView.layer.presentation()
            print(layer?.opacity ?? 0)
        }
        updateLink.isEnabled = true
        updateLink.requiresContinuousUpdates = true

        UIView.animate(withDuration: 10) {
            self.redView.alpha = 1
        } completion: { _ in
            self.updateLink.isEnabled = false
        }
    }
}
UIUpdateLink.gif

注意:UIUpdateLink 只能在主线程中使用。

上一篇下一篇

猜你喜欢

热点阅读