iOS18适配指南之UITrait

2024-09-13 15:00:04 浏览数 (1)

介绍

系统能够自动监听并且处理特征值的改变,不再需要UITraitChangeObservable协议中的特征变化注册方法registerForTraitChanges()

使用

  • 代码。
代码语言:swift复制
import UIKit

class CustomView: UIView {
    override init(frame: CGRect) {
        super.init(frame: frame)
    }

    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    override func layoutSubviews() {
        super.layoutSubviews()

        // iOS18之后自动处理
        if traitCollection.userInterfaceStyle == .dark {
            backgroundColor = .red
        } else {
            backgroundColor = .green
        }
    }
}

class ViewController: UIViewController {
    lazy var customView: CustomView = {
        let customView = CustomView(frame: CGRect(x: 0, y: 0, width: 100, height: 100))
        customView.center = view.center
        return customView
    }()

    override func viewDidLoad() {
        super.viewDidLoad()

        view.addSubview(customView)
    }

    override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()

        // iOS18之后自动处理
        if traitCollection.userInterfaceStyle == .dark {
            view.backgroundColor = .white
        } else {
            view.backgroundColor = .black
        }
    }
}
  • 效果。
UITrait.gifUITrait.gif

注意

该方式在以下方法中自动生效。

  1. UIView:draw()layoutSubviews()updateConstraints()
  2. UIViewController:viewWillLayoutSubviews()viewDidLayoutSubviews()updateViewConstraints()updateContentUnavailableConfiguration()

0 人点赞