iOS26适配指南

iOS26适配指南之Update Properties

2025-06-25  本文已影响0人  YungFan

介绍

自动追踪

案例

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

效果

手动更新
上一篇 下一篇

猜你喜欢

热点阅读