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()
}
}