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 小时前
【大模型微调与部署03】—— ms-swift-3.12 命令行参数(训练、推理、对齐、量化、部署全参数)
开发语言·ios·swift
SameX1 小时前
删掉ML推荐、砍掉五时段分析——做专注App时我三次推翻自己,换来了什么
ios
YJlio2 小时前
2026年4月19日60秒读懂世界:从学位扩容到人形机器人夺冠,今天最值得关注的6个信号
python·安全·ios·机器人·word·iphone·7-zip
90后的晨仔15 小时前
《SwiftUI 高级特性第1章:自定义视图》
ios
空中海16 小时前
第二章:SwiftUI 视图基础
ios·swiftui·swift
空中海18 小时前
第七章:iOS网络与数据持久化
网络·ios
空中海19 小时前
第六章:iOS导航与路由系统
macos·ios·cocoa
空中海19 小时前
第九章:iOS系统框架与能力
macos·ios·cocoa
择势20 小时前
MVVM 本质解构 + RxSwift 与 Combine 深度对决与选型指南
swiftui·swift·rxswift
空中海20 小时前
第三章:布局与组件系统
ios