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("动画完成")
            }
        }
    }
}
  • 效果。
相关推荐
二流小码农9 小时前
鸿蒙开发:一键更新的内测打包工具“火了”
android·ios·harmonyos
kymjs张涛14 小时前
零一开源|前沿技术周报 #8
前端·ios·kotlin
瓜子三百克1 天前
Swift6.1 - 基础知识1: 简单值、控制流、函数和闭包
开发语言·swift
名字不要太长 像我这样就好1 天前
【iOS】消息传递和消息转发
开发语言·学习·macos·ios·objective-c
rit84324991 天前
gin数据解析和绑定
ios·iphone·gin
名字不要太长 像我这样就好1 天前
【iOS】编译和链接、动静态库及dyld的简单学习
笔记·学习·macos·ios·objective-c·cocoa
songgeb2 天前
Currying and Partial application
swift·函数式编程
安和昂2 天前
iOS 通知机制及底层原理
macos·ios·cocoa
白玉cfc2 天前
【iOS】ZARA仿写
macos·ios·cocoa