首页
学习
活动
专区
圈层
工具
发布
社区首页 >专栏 >iOS26适配指南之Update Properties

iOS26适配指南之Update Properties

作者头像
YungFan
发布2025-06-27 09:41:15
发布2025-06-27 09:41:15
4550
举报
文章被收录于专栏:学海无涯学海无涯

介绍

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

自动追踪

案例

代码语言:javascript
复制
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"
    }
}

效果

手动更新

案例

代码语言:javascript
复制
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()
    }
}

效果

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2025-06-26,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 介绍
  • 自动追踪
    • 案例
    • 效果
  • 手动更新
    • 案例
    • 效果
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档