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

Cách lấy chiều cao Navigation Bar trong iOS

Navigation Bar xuất hiện ở đầu màn hình app. Cần biết chiều cao để layout content chính xác, đặc biệt khi custom navigation bar hoặc transparent bar.

Cách lấy chiều cao Navigation Bar trong iOS

Code lấy chiều cao


import UIKit

class ViewController: UIViewController {
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        // Chiều cao Status Bar + Navigation Bar
        let statusBarHeight = UIApplication.shared.statusBarFrame.height
        let navBarHeight = navigationController?.navigationBar.frame.height ?? 0
        let totalHeight = statusBarHeight + navBarHeight
        
        print("Status Bar: \(statusBarHeight)")      // 20 (notch: 44-47)
        print("Navigation Bar: \(navBarHeight)")     // 44 (standard), 52 (large title)
        print("Total: \(totalHeight)")               // 64, 88, 96...
    }
}

Các giá trị tham chiếu

Thiết bị / Chế độ Status Bar Nav Bar Total
iPhone non-notch (SE, 8) 20 44 64
iPhone notch (X, 11, 12, 13, 14, 15) 44-47 44 88-91
iPhone notch + Large Title 44-47 96 140-143
iPad 20 44/50 64/70
Landscape (notch) 0 44 44

Cách hiện đại: Safe Area Insets (iOS 11+)

Thay vì tính toán thủ công, dùng view.safeAreaInsets:


override func viewDidLayoutSubviews() {
    super.viewDidLayoutSubviews()
    
    let topInset = view.safeAreaInsets.top // Tự động = statusBar + navBar (nếu nav bar không transparent)
    print("Safe Area Top Inset: \(topInset)")
    
    // Layout content dưới nav bar
    contentView.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor).isActive = true
}

Khi Navigation Bar Transparent

Nếu nav bar transparent, safeAreaInsets.top chỉ = status bar height. Cần tự cộng thêm nav bar height nếu muốn content bắt đầu dưới nav bar:


let navBarHeight = navigationController?.navigationBar.frame.height ?? 44
let contentTopInset = view.safeAreaInsets.top + navBarHeight

Lưu ý

  • Luôn lấy height trong viewDidLayoutSubviews hoặc viewWillLayoutSubviews (frame đã 확정)
  • viewDidLoad frame chưa chính xác (chưa layout)
  • iOS 15+: Navigation bar height có thể thay đổi khi scroll (standard vs scrollEdge)
  • Không hardcode 44/64/88 - luôn tính động