介紹
系統(tǒng)能夠自動監(jiān)聽并且處理特征值的改變诗良,不再需要UITraitChangeObservable
協(xié)議中的特征變化注冊方法registerForTraitChanges()
。
使用
- 代碼。
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
}
}
}
- 效果。
注意
該方式在以下方法中自動生效脸秽。
- UIView:
draw()
、layoutSubviews()
蝴乔、updateConstraints()
记餐。 - UIViewController:
viewWillLayoutSubviews()
、viewDidLayoutSubviews()
薇正、updateViewConstraints()
剥扣、updateContentUnavailableConfiguration()
。