iOS15でAppearanceの仕様が変わったので詳しく調べてみました。
Appearanceとは
AppearanceとはUIKitの機能の一つで、デフォルトの色やフォントなどを設定できます。
例えばアプリ起動時に下の処理を入れるとナビゲーションバーが青色になります。
UINavigationBar.appearance().barTintColor = UIColor(red: 220/255, green: 0/255, blue: 0/255, alpha: 1)
これ以外にもUILabelのデフォルト文字サイズやUISwitchのデフォルトの色など様々な設定が可能です。
iOS15での変更点
iOS15では既存の方法ではUINavigationBarの色を正しく変更できません。
スクロール位置が一番上のときは下のように真っ白、それ以外の時は青色になります。
iOS15からは下のようにstandardAppearanceとscrollEdgeAppearanceにセットする必要があります。
barTintColorがbackgroundColorに変わっていたりするので、セットする際は注意が必要です。
let appearance = UINavigationBarAppearance()
appearance.backgroundColor = UIColor(red: 220/255, green: 0/255, blue: 0/255, alpha: 1)
UINavigationBar.appearance().standardAppearance = appearance
UINavigationBar.appearance().scrollEdgeAppearance = appearance
上の2つappearanceですが登場はiOS13です。
iOS13とiOS14ではstandardAppearanceだけセットすればUINavigationBar.appearance()のセットと同じような挙動になりました。
standardAppearanceとscrollEdgeAppearanceについて
scrollEdgeAppearanceはスクロール位置が一番上の時に使われるAppearanceでstandardAppearanceはそれ以外に使われるAppearanceです。
そのためscrollEdgeAppearanceだけセットするとスクロール位置が一番上の時だけ設定が反映されます。
それぞれについてのAppleの説明は下のとおりです。
下を見る限りscrollEdgeAppearanceを使わない場合は自動的にstandardAppearanceに見るようです。
そのため今後のアップデートでstandardAppearanceのみセットすれば良くなるかもしれません。
standardAppearance…Describes the appearance attributes for the navigation bar to use when it is displayed with its standard height.
scrollEdgeAppearance…Describes the appearance attributes for the navigation bar to use when an associated UIScrollView has reached the edge abutting the bar (the top edge for the navigation bar). If not set, a modified standardAppearance will be used instead.
その他
Appearanceですが上記以外に下の2つがあります。
こちらはナビゲーションバーが小さい時(画面を横向きにした時)に使われるAppearanceです。
compactAppearance
compactScrollEdgeAppearance
下のようにセットすると横向きの時だけナビゲーションバーが赤くなります。
compactScrollEdgeAppearanceだけはiOS15からなのでavailableで判定しています。
let appearance = UINavigationBarAppearance()
appearance.backgroundColor = UIColor(red: 65/255, green: 105/255, blue: 225/255, alpha: 1)
UINavigationBar.appearance().standardAppearance = appearance
UINavigationBar.appearance().scrollEdgeAppearance = appearance
let appearance2 = UINavigationBarAppearance()
appearance2.backgroundColor = UIColor(red: 225/255, green: 105/255, blue: 65/255, alpha: 1)
UINavigationBar.appearance().compactAppearance = appearance2
if #available(iOS 15.0, *) {
UINavigationBar.appearance().compactScrollEdgeAppearance = appearance2
}
また、UILabelなどスクロールが関係ないものは今まで通り使うことができます。
UILabel.appearance().font = .systemFont(ofSize: 24)