LoginSignup
17
4

More than 1 year has passed since last update.

SwiftUIでUIKitのビューの装飾をするためにUIAppearanceを使うのは間違っている

Last updated at Posted at 2021-11-20

SwiftUIはツールバーの背景色を変えることができません。
この問題に対応するために、UIAppearanceを利用する記事が散見されます。
実際、次のようなコードを書くことでTabViewの背景色を変えることができます。

struct ContentView: View {
    var body: some View {
        NavigationView {
            Text("button")
            .toolbar {
                ToolbarItem(placement: .bottomBar){
                    Text("Item")
                }
            }
        }
        .onAppear {
            UIToolbar.appearance().backgroundColor = UIColor.blue
        }
    }
}

CleanShot 2021-11-21 at 04.30.33@2x.png

しかし、この手法を利用することはオススメしません。
UIAppearanceは指定したクラスのアプリ全体の装飾を変えるメソッドのため、意図しない画面を侵食する可能性があるためです。

実際に、このまま次のViewControllerを表示してみましょう。

class ViewController: UIViewController {
    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = .lightGray
        navigationController?.setToolbarHidden(false, animated: false)
        setToolbarItems([.init(title: "Button", style: .done, target: nil, action: nil)], animated: false)
    }
}

CleanShot 2021-11-21 at 04.33.18@2x.png

ViewControllerのtoolbarは色の指定が無いにも関わらず、背景色が変更されています。
このように、UIAppearanceを使うことで目的と違う画面のUI装飾を変えてしまいました。

これは、たった1画面のUI装飾を変えるためにアプリケーション全体で使われるUIを網羅的に検査し、漏れなく装飾の適用を打ち消す処理を書く必要があるともいえます。

自分の書くUIならともかく、サードパーティなどの修正不可な箇所にも影響が出る可能性はあります。
そういうことです。

17
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
17
4