iOS26适配指南之Update Properties

1,506 阅读1分钟

介绍

  • UIViewController 与 UIView 均增加了一个名为updateProperties()的新方法,可以通过修改属性值达到更新 UI 的效果。
  • 它是一种轻量级的 UI 更新方式,不会触发完整的布局过程(不会触发layoutSubviews()或者viewWillLayoutSubviews()方法)。常见使用场景如下。
    • 更改 UI 的内容。
    • 显示/隐藏 UI。
    • 无需移动或者调整 UI 的大小。
  • 可以自动追踪 @Observable Object。
  • 可以通过调用setNeedsUpdateProperties()方法手动触发更新。

自动追踪

案例

import UIKit

@Observable class Model {
    var currentColor: UIColor = .systemGray
    var currentValue: String = "WWDC26"
}

class ViewController: UIViewController {
    lazy var label: UILabel = {
        let label = UILabel()
        label.frame = CGRect(x: 0, y: 0, width: 300, height: 60)
        label.textAlignment = .center
        label.font = UIFont.boldSystemFont(ofSize: 64)
        label.center = view.center
        return label
    }()
    let model = Model()

    override func viewDidLoad() {
        super.viewDidLoad()

        view.addSubview(label)
    }

    override func updateProperties() {
        super.updateProperties()

        label.textColor = model.currentColor
        label.text = model.currentValue
    }

    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        model.currentColor = .systemBlue
        model.currentValue = "iOS26"
    }
}

效果

自动追踪.gif

手动更新

案例

import UIKit

class Model {
    var currentColor: UIColor = .systemBlue
    var currentValue: String = "WWDC26"
}

class ViewController: UIViewController {
    lazy var label: UILabel = {
        let label = UILabel()
        label.frame = CGRect(x: 0, y: 0, width: 300, height: 60)
        label.textAlignment = .center
        label.font = UIFont.boldSystemFont(ofSize: 64)
        label.center = view.center
        return label
    }()
    let model = Model()

    override func viewDidLoad() {
        super.viewDidLoad()

        view.addSubview(label)
    }

    override func updateProperties() {
        super.updateProperties()

        label.textColor = model.currentColor
        label.text = model.currentValue
    }

    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        model.currentColor = .systemGray
        model.currentValue = "iOS26"
        // 手动更新
        setNeedsUpdateProperties()
    }
}

效果

手动更新