Trait
概要
Trait とは、アプリケーションが実行されている環境を説明するもの。
Traits describe the environment that your application is running in.
例えば、Trait の例として horizontalSizeClass がある。これは、水平方向の利用可能な空間に対してどのような体験を提供すべきか、を説明する Trait であり、Regular, Compact, Unspecified の3つのうちどれかの値をとる。Trait 自体は具体的な値に紐づかないのが特徴。
Trait にはいくつかの種類がある。最も一般的なのは Size Class。
Layout に関する Trait
Size Classes (水平/垂直方向のサイズ)
Dynamic Type (フォントサイズ)
Layout Direction (右->左 or 左->右)
Appearance に関する Trait
Display Gamut (色域)
Interface Style (light/Dark, Apple TV のみ)
Capabilities に関する Trait
3D Touch (サポートの有無)
UITraitCollection
iOS のインタフェース環境を表現する オブジェクト。各種 Trait を保持する。UITraitEnvironment プロトコルを実装したオブジェクトの場合は、traitCollection プロパティ経由で露出している。このプロトコルは、UIScreen, UIWindow, UIViewController, UIView 等のクラスで実装されている。Adaptiveなアプリケーションを作成するためには、この Trait に応じてアプリケーションのレイアウトを変更するコードを書かなくてはならない。
インタフェース環境に応じてレスポンシブにしたい場合はUITraitEnvironment プロトコルの traitCollectionDidChange(_:) をオーバーライドする。UITraitCollection は、各種オブジェクト間で伝達されていき、その中で traitCollectionDidChange(_:) が呼び出される。この伝達の最中に内容が変化する場合もある。例えば、UISplitViewController は、primary (master) と secondary (detail) の ViewController に UITraitCollection を伝達する際に、horizontalSizeClass を変更して伝える場合がある。
https://gyazo.com/a5c12717e95dc5c9c23cd46de90c09ba
インタフェース環境の変更に応じたアニメーションをカスタマイズしたい場合は UIContentContainer プロトコルの willTransition(to:with:) をオーバーライドする。
table:UITraitCollection
プロパティ名 値の型 概要
horizontalSizeClass UIUserInterfaceSizeClass 水平方向の Size Class
verticalSizeClass UIUserInterfaceSizeClass 垂直方向の Size Class
displayScale CGFloat 表示スケール。1.0 は non-Retina, 2.0 は Retina ディスプレイを示す
userInterfaceIdiom UIUserInterfaceIdiom
自動的なTraitへの応答
traitColleciotnDidChange(_:) 内で全ての変更をハンドリングするのは大変なので、自動的に応答するシステムがいくつかある。
Interface Builder
Interface Builder 内で Adaptibity と Size Class を利用している場合は、システムは UITraitCollection の変更時に自動的に応答してくれる
Asset Catalog
様々な色域, Size Class, Scale factor に対して画像を指定できる
UIAppearance
AppleTVの明暗モード用に異なる配色を設定すると、traitCollectionDidChange 時に自動で適用される
参考
https://developer.apple.com/videos/play/wwdc2016/222/
https://developer.apple.com/documentation/uikit/uitraitcollection