Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> iOS

Cách đặt màu nền cho Navigation Bar trong iOS

Để đặt màu nền (background color) cho UINavigationBar, có thể làm qua Storyboard hoặc code. Từ iOS 13+, khuyến khích dùng UINavigationBarAppearance để nhất quán.

Phương pháp 1: Storyboard Editor

  1. Chọn View Controller > Editor > Embed In > Navigation Controller.
  2. Chọn Navigation Bar (thanh trên cùng) trong Document Outline.
  3. Attribute Inspector > Bar Tint (màu nền) & Tint (màu nút/title).

Cách đặt màu nền cho Navigation Bar trong iOS

Phương pháp 2: Code (iOS 13+ - Khuyến khích)

Dùng UINavigationBarAppearance để cấu hình toàn diện:


override func viewDidLoad() {
    super.viewDidLoad()
    configureNavigationBar()
}

func configureNavigationBar() {
    let appearance = UINavigationBarAppearance()
    appearance.configureWithOpaqueBackground()  // Nền không trong suốt
    appearance.backgroundColor = .systemBlue    // Màu nền
    appearance.titleTextAttributes = [
        .foregroundColor: UIColor.white,        // Màu title
        .font: UIFont.boldSystemFont(ofSize: 18)
    ]
    appearance.largeTitleTextAttributes = [
        .foregroundColor: UIColor.white
    ]
    
    // Áp dụng cho standard, compact, scrollEdge
    navigationController?.navigationBar.standardAppearance = appearance
    navigationController?.navigationBar.compactAppearance = appearance
    navigationController?.navigationBar.scrollEdgeAppearance = appearance
    
    // Tint color cho nút back, button items
    navigationController?.navigationBar.tintColor = .white
    
    // Bật large title nếu muốn
    navigationController?.navigationBar.prefersLargeTitles = true
    title = "Trang chủ"
}

Phương pháp 3: Code cũ (iOS < 13, vẫn hoạt động)


// Chỉ đổi màu nền
navigationController?.navigationBar.barTintColor = .systemBlue

// Màu chữ title
navigationController?.navigationBar.titleTextAttributes = [
    NSAttributedString.Key.foregroundColor: UIColor.white
]

// Màu nút back/button items
navigationController?.navigationBar.tintColor = .white

// Tắt trong suốt
navigationController?.navigationBar.isTranslucent = false

Global Appearance (Toàn app)

Trong AppDelegate hoặc SceneDelegate:


let appearance = UINavigationBarAppearance()
appearance.configureWithOpaqueBackground()
appearance.backgroundColor = .systemBlue
appearance.titleTextAttributes = [.foregroundColor: UIColor.white]
appearance.largeTitleTextAttributes = [.foregroundColor: UIColor.white]

UINavigationBar.appearance().standardAppearance = appearance
UINavigationBar.appearance().compactAppearance = appearance
UINavigationBar.appearance().scrollEdgeAppearance = appearance
UINavigationBar.appearance().tintColor = .white

Lưu ý

  • barTintColor (cũ) không hoạt động nếu đã set appearance.
  • isTranslucent = false cần thiết cho màu nền hiển thị đúng (trừ khi dùng appearance.configureWithOpaqueBackground).
  • Large Title (iOS 11+) cần prefersLargeTitles = true và scrollEdgeAppearance.