iOS26适配指南之动画

介绍

新增了一种新的动画选项flushUpdates,它可以自动根据 @Observable Object 或者 AutoLayout 约束的更改添加动画效果,而无需手动调用layoutIfNeeded()方法。

使用

  • 代码。
swift 复制代码
import UIKit

@Observable class Model {
    var backgroundColor: UIColor = .systemGray
}

class ViewController: UIViewController {
    lazy var redView: UIView = {
        let view = UIView(frame: CGRect(x: 0, y: 50, width: 100, height: 100))
        view.backgroundColor = .systemRed
        view.translatesAutoresizingMaskIntoConstraints = false
        return view
    }()
    var widthConstraint: NSLayoutConstraint!
    var heightConstraint: NSLayoutConstraint!
    let model = Model()

    override func viewDidLoad() {
        super.viewDidLoad()

        view.addSubview(redView)

        widthConstraint = redView.widthAnchor.constraint(equalToConstant: 100)
        heightConstraint = redView.heightAnchor.constraint(equalToConstant: 100)
        widthConstraint.isActive = true
        heightConstraint.isActive = true
        redView.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
        redView.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true
    }

    override func viewWillLayoutSubviews() {
        super.viewWillLayoutSubviews()
        view.backgroundColor = model.backgroundColor
    }

    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        // UIView动画
        UIView.animate(withDuration: 2.0, delay: 0, options: .flushUpdates) {
            self.model.backgroundColor = .systemBlue
        } completion: { _ in
            // UIViewPropertyAnimator动画
            _ = UIViewPropertyAnimator.runningPropertyAnimator(withDuration: 2.0,
                                                               delay: 0,
                                                               options: .flushUpdates) {
                self.widthConstraint.constant = 300
                self.heightConstraint.constant = 300
            } completion: { _ in
                print("动画完成")
            }
        }
    }
}
  • 效果。
相关推荐
东坡肘子1 天前
Swift 还让你 Excited 吗?-- 肘子的 Swift 周报 #141
人工智能·swiftui·swift
壹方秘境2 天前
我用Go语言开发了一个跨平台的HTTPS抓包和调试工具
前端·后端·ios
sweet丶4 天前
Swift 元编程-Macro
swift
初级代码游戏7 天前
easy Photo Clean公测版:快速清理iPhone照片 邀请公测
ios·iphone
库奇噜啦呼7 天前
【iOS】RunLoop学习
学习·ios
影寂ldy7 天前
WinForm PictureBox控件 + ImageList组件 完整笔记
开发语言·笔记·swift
黑科技iOS上架7 天前
iOS应用周末提交什么情况算卡审
经验分享·ios
zzb15807 天前
ios基础-MVC-UIView
ios·mvc·cocoa
kingbal7 天前
Flutter:Flutter SDK版本管理工具FVM
android·flutter·ios·android-studio·window