기어가더라도 제대로

[UIKit-기초] UINavigationBar Cheat Sheet - 1 본문

UIKit 기초

[UIKit-기초] UINavigationBar Cheat Sheet - 1

Damagucci-juice 2025. 2. 7. 19:00
 자주 쓰는 초식을 전개해 봤습니다.

 

아래의 초식들은 viewDidLoad 함수나, 전역적으로 선언한다면 AppDelegate에 하는 것이 좋습니다. 

타이틀 영역에 이미지를 넣고 이를 좌측 정렬, 왼쪽으로 밀기

  • appearance 선언과 설정은 자주 나와서 처음만 보여드리고 생략
// appearance 선언
let appearance = UINavigationBarAppearance()
appearance.configureWithOpaqueBackground()

// 상단 이미지 로고 뷰 생성
let logoImageView = UIImageView(image: UIImage(resource: <#Image#>))
logoImageView.contentMode = .scaleAspectFit

// 이미지 뷰를 타이틀로 선언
navigationItem.titleView = logoImageView

//  타이틀 이미지 좌측 정렬
appearance.titlePositionAdjustment = UIOffset(horizontal: -(view.frame.width/2),
                                              vertical: 0)
                                              
// appearance 설정
navigationItem.standardAppearance = appearance
navigationItem.scrollEdgeAppearance = appearance
navigationItem.compactAppearance = appearance

 

오른쪽 상단 영역에 버튼 설정

  • 버튼 항목들을 스택뷰로 감싸 NavigationItem.rightBarButton에 설정하는 개념
// QR 스캔 버튼
let scanButton = UIButton(type: .custom)
scanButton.setImage(UIImage(resource: .qrCodeSmall), for: .normal)
scanButton.tintColor = .darkGray
scanButton.addTarget(self, action: #selector(scanButtonTapped), for: .touchUpInside)

// 검색 버튼
let searchButton = UIButton(type: .custom)
searchButton.setImage(UIImage(resource: .searchSmall), for: .normal)
searchButton.tintColor = .darkGray
searchButton.addTarget(self, action: #selector(searchButtonTapped), for: .touchUpInside)

// 스택뷰에 포함
let stackView = UIStackView(arrangedSubviews: [scanButton, searchButton])
stackView.distribution = .equalSpacing
stackView.axis = .horizontal
stackView.alignment = .center
stackView.spacing = 16

// 스택뷰를 설정
navigationItem.rightBarButtonItem = UIBarButtonItem(customView: stackView)

 

뒤로가기 버튼 제목 지우기, Back Button title

  • 개별 뷰컨트롤러의 경우 타겟하는 VC로 들어가기 전에 VC에서 설정을 해줘야합니다. 
  • 예시) 'B VC의 "뒤로가기" 백버튼 타이틀을 지우고 싶다'
    • A VC에서 아래코드 실행 -> B VC로 이동
navigationItem.backBarButtonItem = UIBarButtonItem(
    title: nil,
    style: .plain,
    target: nil,
    action: nil
)
Comments