1
1

More than 1 year has passed since last update.

【SwiftUI】NavigationBarの背景色を半透明にする方法

Last updated at Posted at 2023-01-10

はじめに

iOS標準メモアプリのNavigationBarって実は半透明なんですよ
今回はそれを再現します。

環境

  • Xcode14.2
  • iOS16.2

UIBarAppearanceを使う方法

import SwiftUI

struct ContentView: View {
    @State private var text = ""
    
    init() {
        UINavigationBar.appearance().standardAppearance = {
           let appearance = UINavigationBarAppearance() // 1
            appearance.configureWithTransparentBackground() // 2
            appearance.backgroundColor = .systemBackground.withAlphaComponent(0.9) // 3
            return appearance
        }()
    }
    
    var body: some View {
        NavigationStack {
            TextEditor(text: $text)
                .ignoresSafeArea()
                .navigationTitle("タイトル")
                .navigationBarTitleDisplayMode(.inline)
        }
    }
}
  1. ナビゲーションバーの外観をカスタマイズするためのオブジェクト
  2. 影をなくし、背景を透明にする
  3. 背景色を不透明度0.9の UIColor.systemBackground にする

UIBarAppearanceを使わない方法

import SwiftUI

struct ContentView: View {
    @State private var text = ""
    
    var body: some View {
        NavigationStack {
            GeometryReader { geometryProxy in
                TextEditor(text: $text)
                    .ignoresSafeArea()
                    .navigationTitle("タイトル")
                    .navigationBarTitleDisplayMode(.inline)
                    .toolbarBackground(.hidden, for: .navigationBar)
                    .overlay(alignment: .top) {
                        Color(.systemBackground).opacity(0.9)
                            .frame(height: geometryProxy.safeAreaInsets.top)
                            .ignoresSafeArea()
                    }
            }
        }
    }
}

スクリーンショット

94EF94B8-906A-498A-A859-7C228951BB14_1_201_a.jpeg

おわり

開放感があってかっこいいですね。ぜひ試してみてください。


ご覧いただきありがとうございました。

🐦 Twitter: @shota_appdev

📱 個人アプリ: Symbols Explorer

1
1
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
1
1